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);
The answer given as correct is no good for counting things like line returns and is far too verbose. Later answers are better but all can be achieved simply with
It does not drop trailing matches using the example in the question.
This solution prints the total number of occurrence of a given substring throughout the string, also includes the cases where overlapping matches do exist.
}
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
So your
lastindex
value is always 0 and it always finds hello in the string.You can number of occurrences using inbuilt library function:
Try this one. It replaces all the matches with a
-
.And if you don't want to destroy your
str
you can create a new string with the same content:After executing this block these will be your values: