Why is the following algorithm not halting for me? (str is the string I am searching in, findStr is the string I am trying to find)
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);
As @Mr_and_Mrs_D suggested:
How about using StringUtils.countMatches from Apache Commons Lang?
That outputs:
try adding
lastIndex+=findStr.length()
to the end of your loop, otherwise you will end up in an endless loop because once you found the substring, you are trying to find it again and again from the same last position.Here it is, wrapped up in a nice and reusable method:
Based on the existing answer(s) I'd like to add a "shorter" version without the if:
A shorter version. ;)