为什么以下算法对我没有停止? (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);
最佳答案
如何使用StringUtils.countMatches来自 Apache Commons Lang?
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(StringUtils.countMatches(str, findStr));
输出:
3
关于java - 字符串中子字符串的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/767759/