[英]String.contains in Java
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
都包含空字符串。
沒有給出真正的解釋(在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
會產生誤導。 所有字符串都包含它,因為它什么都沒有 要說它們沒有包含它就意味着空字符串中有一些未被捕獲的物質,這是錯誤的。
將字符串視為一組字符,在數學中,空集始終是任何集的子集。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.