为什么 contains() 方法在 Java 中的非空字符串中查找空字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18399189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does contains() method find empty string in non-empty string in Java
提问by george_h
This is a weird behavior I found with Java's String.indexOf()
and String.contains()
methods. If I have a non-emptystring 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
.
这是我在 JavaString.indexOf()
和String.contains()
方法中发现的一种奇怪的行为。如果我有一个非空字符串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?
从逻辑上讲(至少对我而言)""
不会发生在blablablabla
但indexOf("")
说会发生,为什么?
采纳答案by nanofarad
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. 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.
在任何字符串的开头、结尾和字符之间都存在一组空的 char 值。从任何东西中,你都不能提取任何东西。从一根实际的绳子/纱线中,我可以说其中存在零长度部分。
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。
回答by Xabster
""
occurs between every character and also at start and end.
""
出现在每个字符之间以及开始和结束处。