为什么下面的算法对我来说没有停止?(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);
发布于 2009-04-20 11:41:26
最后一行是在制造一个问题。lastIndex
永远不会是-1,所以会有一个无限循环。这可以通过将最后一行代码移到if块中来修复。
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);
发布于 2009-04-21 11:16:17
使用Apache Commons Lang中的StringUtils.countMatches怎么样?
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(StringUtils.countMatches(str, findStr));
这将输出以下内容:
3
发布于 2009-04-20 11:10:12
您的lastIndex += findStr.length();
被放在括号之外,导致无限循环(当没有找到任何匹配项时,lastIndex始终为findStr.length()
)。
修复后的版本如下:
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);
https://stackoverflow.com/questions/767759
复制相似问题