为什么下面的算法不能停止?str 是搜索的字符串, findStr 是我要找的字符串。
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count =0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if( lastIndex != -1){
count ++;
}
lastIndex+=findStr.length();
}
System.out.println(count);
lastIndex = str.indexOf(findStr,lastIndex);
返回 findStr 子字符串在 str 字符串中第一次出现处的 索引 ,从指定的 lastIndex 索引开始。因为lastIndex=0;所以第一次查找得到的索引还是0。
应该把下面的 lastIndex+=findStr.length();放到while循环中;这样不会死循环了。
lastIndex+=findStr.length(); str.indexof() 检索到字符串返回字符串的位置 因此str中有次字符串 所以lastIndex永远不等于-1
所以是个死循环
你这个每次进去就是在查hello lastIndex永远为0嘛
lastIndex = str.indexOf(findStr,lastIndex); //确定没有错误????
u010709330 的分析是对的。代码看起来像这样。
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = str.indexOf(findStr, lastIndex);
if (lastIndex != -1) {
count++;
lastIndex += findStr.length();
}
}
System.out.println(count);