为什么以下算法对我来说没有停止? (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);
原文由 bobcom 发布,翻译遵循 CC BY-SA 4.0 许可协议
最后一行造成了一个问题。
lastIndex
永远不会在-1,所以会有一个无限循环。这可以通过将最后一行代码移到 if 块中来解决。