Вопрос-ответ

Find the Number of Occurrences of a Substring in a String

Найти количество вхождений подстроки в строку

Почему следующий алгоритм не останавливается для меня?

В приведенном ниже коде, 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

Как насчет использования StringUtils.countMatches из Apache Commons Lang?

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

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

Это выводит:

3
Ответ 2

Ваше значение 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);
Ответ 3

Более короткая версия. ;)

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(str.split(findStr, -1).length-1);
Ответ 4

Последняя строка создавала проблему. 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);
java string