为什么下面的算法不能停止?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);
5 回答

眼眸繁星
TA贡献1873条经验 获得超9个赞
lastIndex = str.indexOf(findStr,lastIndex);
返回 findStr 子字符串在 str 字符串中第一次出现处的 索引 ,从指定的 lastIndex 索引开始。因为lastIndex=0;所以第一次查找得到的索引还是0。
应该把下面的 lastIndex+=findStr.length();放到while循环中;这样不会死循环了。

不负相思意
TA贡献1777条经验 获得超10个赞
lastIndex+=findStr.length(); str.indexof() 检索到字符串返回字符串的位置 因此str中有次字符串 所以lastIndex永远不等于-1
所以是个死循环

www说
TA贡献1775条经验 获得超8个赞
代码看起来像这样。
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);
添加回答
举报
0/150
提交
取消