Java中的String.contains
String s1 = "The quick brown fox jumps over the lazy dog"; String s2 = ""; boolean b = s1.contains(s2); System.out.println(b);
我运行上面的Java代码,b返回true。 由于s2为空,为什么s1包含s2?
我检查了Java API,它写道:
当且仅当此字符串包含指定的char值序列时,才返回true。
参数:
s – 要搜索的序列
返回:
如果此字符串包含s则返回true,否则返回false
Empty是任何字符串的子集。
把它们想象成每两个字符之间的差异。
在任何大小的线上都有无数个点的方式……
(嗯……我想知道如果我使用微积分连接无数个空字符串会得到什么)
请注意“”.equals(“”)。
同理:
"".contains(""); // Returns true.
因此,似乎任何String
都包含空字符串。
Java没有给出真正的解释(在JavaDoc或令人垂涎的代码注释中),但是看一下代码,看起来这很神奇:
调用堆栈:
String.indexOf(char[], int, int, char[], int, int, int) line: 1591 String.indexOf(String, int) line: 1564 String.indexOf(String) line: 1546 String.contains(CharSequence) line: 1934
码:
/** * Code shared by String and StringBuffer to do searches. The * source is the character array being searched, and the target * is the string being searched for. * * @param source the characters being searched. * @param sourceOffset offset of the source string. * @param sourceCount count of the source string. * @param target the characters being searched for. * @param targetOffset offset of the target string. * @param targetCount count of the target string. * @param fromIndex the index to begin searching from. */ static int indexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex) { if (fromIndex >= sourceCount) { return (targetCount == 0 ? sourceCount : -1); } if (fromIndex < 0) { fromIndex = 0; } if (targetCount == 0) {//my comment: this is where it returns, the size of the return fromIndex; // incoming string is 0, which is passed in as targetCount } // fromIndex is 0 as well, as the search starts from the // start of the source string ...//the rest of the method
我会用数学类比回答你的问题:
在这种情况下,数字0将代表无值。 如果你选择一个随机数,比如15,那么从15中减去多少次0? 无限时间,因为0没有任何价值,因此你从15中取出任何东西。你难以接受15 – 0 = 15而不是ERROR吗? 因此,如果我们将这个类比转回Java编码,则字符串“”表示没有值。 选择一个随机字符串,说“hello world”,可以从“hello world”中减去多少次?
显而易见的答案是“这就是JLS所说的。”
考虑到为什么会这样,考虑到这种行为在某些情况下会很有用。 假设您想要针对一组其他字符串检查字符串,但其他字符串的数量可能会有所不同。
所以你有这样的事情:
for(String s : myStrings) { check(aString.contains(s)); }
其中一些s
是空字符串。
如果空字符串被解释为“无输入”,并且如果您的目的是确保aString
包含myStrings
中的所有“输入”,那么空字符串返回false
会产生误导。 所有字符串都包含它,因为它什么都没有 要说它们没有包含它就意味着空字符串中有一些物质未被捕获在字符串中,这是错误的。
将字符串视为一组字符,在数学中,空集始终是任何集的子集。