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

Donations appreciated. Every little $ helps. Or click Google +1

Related Posts with Thumbnails

7 Responses to “Java Count Number Of Instances Of Substring”

Pages: « 1 [2] Show All

  1. 6
    Jamal Bayer Says:

    I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favorites weblog list and will be checking back soon. Please check out my site as well and let me know what you think.

  2. 7
    Sushil Says:

    Thanks for the code!

Pages: « 1 [2] Show All

Leave a Reply

Spam protection by WP Captcha-Free