简体   繁体   English

为什么contains()方法在Java中的非空字符串中找到空字符串

[英]Why does contains() method find empty string in non-empty string in Java

This is a weird behavior I found with Java's String.indexOf() and String.contains() methods. 这是我在Java的String.indexOf()String.contains()方法中发现的奇怪行为。 If I have a non-empty string says blablabla and I try to look for an empty string inside it, it always returns true whereas I would expect it to return false . 如果我有一个非空字符串说blablabla并且我试图在其中寻找一个空字符串,它总是返回true而我希望它返回false

So basically, why does the code below return true and 0 ? 所以基本上,为什么下面的代码返回true和0?

String testThis = "";
String fileName = "blablablabla";
System.out.println(fileName.contains(testThis));
System.out.println(fileName.indexOf(testThis));

Logically (at least to me) "" does not occur in blablablabla but indexOf("") says it does, why? 逻辑上(至少对我而言) ""不会出现在blablablablaindexOf("")表示它确实存在,为什么?

An empty string occurs in every string. 每个字符串都会出现一个空字符串。 Specifically, a contiguous subset of the string must match the empty string. 具体而言,字符串的连续子集必须与空字符串匹配。 Any empty subset is contiguous and any string has an empty string as such a subset. 任何空子集都是连续的,任何字符串都有一个空字符串作为这样的子集。

Returns true if and only if this string contains the specified sequence of char values. 当且仅当此字符串包含指定的char值序列时,才返回true。

An empty set of char values exists in any string, at the beginning, end, and between characters. 任何字符串,开头,结尾和字符之间都存在一组空值char。 Out of anything, you can extract nothing. 出于任何事情,你什么都不提取。 From a physical piece of string/yarn I can say that a zero-length portion exists within it. 从一条物理的绳子/纱线我可以说它内部存在零长度部分。

If contains returns true there is a possible substring( invocation to get the string to find. "aaa".substring(1,1) should return "" , but don't quote me on that as I don't have an IDE at the moment. 如果contains返回true,则有一个可能的substring(调用以获取要查找的字符串。 "aaa".substring(1,1)应返回"" ,但不要引用我,因为我没有IDE此时此刻。

""出现在每个角色之间以及开始和结束之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM