Java: Example - Count occurences
Problem: Count the number of times one string
is found in another.
//-------------------------------------------- count()
int count(String base, String searchFor) {
int len = searchFor.length();
int result = 0;
if (len > 0) { // search only if there is something
int start = base.indexOf(searchFor);
while (start != -1) {
result++;
start = base.indexOf(searchFor, start+len);
}
}
return result;
}
The loop is a natural
for
loop, but this would produce
a very long line.