为什么以下算法对我来说不停止?(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永远不会为-1,所以会有无限循环。可以通过将代码的最后一行移到if块中来解决此问题。
lastIndex
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);