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.

Related Posts Plugin for WordPress, Blogger...


  1. really now, must we use a ‘while (true)’ loop? That’s extremely poor coding style. That’s the sort of thing I used to do on a graphing calculator when I was younger. With a loop like that, I have to read the entire loop to understand when it breaks.

    Problems I see:
    — No control statement in the while loop.
    — Variable name ‘ctr’ is misleading.. it doesn’t count, it keeps track of the ‘fromIndex’ in your code. therefore the breaking condition is also obscure.
    — You have 2 unneeded if-else statements
    — You’re not letting programming idioms do the work for you

    This is far more idiomatic, and easier to read, and likely lots faster:

    public static int countIndexOf(String text, String search)
        int count = 0;
        int textLength = text.length();

        for (int fromIndex = 0; fromIndex > -1; count++)
            fromIndex = attributesList.indexOf(search, fromIndex + ((count > 0) ? 1 : 0));

        return count - 1;

    I would have cast that boolean (count > 0) into an int, but Java likes to make simple tasks like that harder than it should be.

    Benefits to this solution:
    — The ‘length()’ property of the strings is not evaluated *every* loop iteration.
    — Simple ‘for’ statement: start at the beginning of the string, go while the substring is found, and add one to count each time.
    — No need for if-else’ing in the middle of the loop. It handles itself.

    Drawbacks to this solution:
    — Had to do a ternary statement in the middle of the ‘.indexOf’ call. could have been avoided if java supported simple boolean casting into int: “fromIndex + (count > 0)”. The reason I had to do this is because a substring occurrence at index 0 would be missed if I kept it as just “fromIndex + 1”.
    — variable ‘count’ comes out 1 too high because of the for loop. Just return the value – 1.

  2. haha, oops! I left a bad variable name in that code snippet 🙂 artifact from my own coding.

    public static int countIndexOf(String text, String search)
        int count = 0;
        int textLength = text.length();
        for (int fromIndex = 0; fromIndex > -1; count++)
            fromIndex = text.indexOf(search, fromIndex + ((count > 0) ? 1 : 0));

        return count – 1;

  3. Please note that the first and last variant of the function are not really equal in any case:

    “ctr += search.length();”


    “fromIndex + ((count > 0) ? 1 : 0)”

    In one case, the whole length of the “search” string is skipped, in the other case, only one character is skipped. If for example, the “text” variable is “AAAAAA” and the “search” variable is “AA”, the results will be:
    “3” in the first case, “5” in the second one. I think, “3” is correct here, but it may depend on your other code, which of the two variants you need.

  4. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *