Java Count Number Of Instances Of Substring

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;
}

Like what you see? Buy me a cup of coffee. Or subscribe to my feeds.