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);
Do you really have to handle the matching yourself ? Especially if all you need is the number of occurences, regular expressions are tidier :
If you need the index of each substring within the original string, you can do something with indexOf like this:
This below method show how many time substring repeat on ur whole string. Hope use full to you:-
}
A lot of the given answers fail on one or more of:
Here's what I wrote:
Example call:
If you want a non-regular-expression search, just compile your pattern appropriately with the
LITERAL
flag:Increment
lastIndex
whenever you look for next occurrence.Otherwise it's always finding the first substring (at position 0).