Java Count Number Of Instances Of Substring
Posted by tech on
April 16, 2008
This is a handy Java method that will count the number of instances of a substring within the String object.
public static int countIndexOf(String content, String search) {
int ctr = -1;
int total = 0;
while (true) {
if (ctr == -1) ctr = content.indexOf(search);
else ctr = content.indexOf(search, ctr);
if (ctr == -1) {
break;
} else {
total++;
ctr += search.length();
}
}
return total;
}







