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);
Your
lastIndex += findStr.length();
was placed outside the brackets, causing an infinite loop (when no occurence was found, lastIndex was always tofindStr.length()
).Here is the fixed version :
here is the other solution without using regexp/patterns/matchers or even not using StringUtils.
The last line was creating a problem.
lastIndex
would never be at -1, so there would be an infinite loop. This can be fixed by moving the last line of code into the if block.at the end of the loop count is 3; hope it helps
I'm very surprised no one has mentioned this one liner. It's simple, concise and performs slightly better than
str.split(target, -1).length-1
Here is the advanced version for counting how many times the token occurred in a user entered string: