2 - - - - 1 совпадает с 2 - (- (- (- 1))), что аналогично
2 - (- (1)) = 2 + 1 = 3
Как только количество минусов становится четным, вы фактически делаете «+».
Последняя строка создала проблему. 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);
Укороченная версия. ;)
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(str.split(findStr, -1).length-1);
попробуйте добавить lastIndex + = findStr.length ()
в конец цикла, в противном случае вы окажется в бесконечном цикле, потому что как только вы нашли подстроку, вы пытаетесь найти ее снова и снова из той же самой последней позиции.
public int indexOf(int ch,
int fromIndex)
Возвращает индекс в этой строке первого вхождения указанного символа, начиная поиск по указанному индексу.
Таким образом, ваше значение lastindex
всегда равно 0, и оно всегда находит привет в строке.
Увеличивайте lastIndex
всякий раз, когда вы ищете следующее вхождение.
В противном случае он всегда находит первую подстроку (в позиции 0).
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) {
count++;
lastIndex += findStr.length() - 1;
}
System.out.println(count);
в конце счетчика цикла равен 3; надеюсь, это поможет
Вы действительно должны сами справиться с соответствием? Особенно, если вам нужно только количество вхождений, регулярные выражения более аккуратны:
String str = "helloslkhellodjladfjhello";
Pattern p = Pattern.compile("hello");
Matcher m = p.matcher(str);
int count = 0;
while (m.find()){
count +=1;
}
System.out.println(count);
Ваш 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);
Как насчет использования StringUtils.countMatches из Apache Commons Lang?
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(StringUtils.countMatches(str, findStr));
Что выводит:
3