字符串中子字符串的出现次数

2022-08-31 07:32:31

为什么以下算法没有为我停止?(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);

答案 1

使用来自Apache Commons Lang的StringUtils.countMatches怎么样?

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

System.out.println(StringUtils.countMatches(str, findStr));

输出:

3

答案 2

您被放置在括号之外,导致无限循环(当没有找到任何事件时,lastIndex总是到)。lastIndex += findStr.length();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);