0

I looked through the String API in Java 6 and I did not find any method for computing how many times a specific sub-string appears within a given String.

For example, I would like to know how many times "is" or "not" appears in the string "noisxxnotyynotxisi".

I can do the long way with a loop, but I would like to know whether there is a simpler way.

Thanks.

Edit: I'm using Java 6.

3 Answers 3

4

org.apache.commons.lang.StringUtils.countMatches method could be preferred.

Sign up to request clarification or add additional context in comments.

Comments

2

Without using an external library, you can use String.indexOf(String str, int fromIndex); in a loop.


Update This example fully works.

/**
 * @author The Elite Gentleman
 * @since 31 March 2011
 *
 */
public class Test {

    private static final String STR = "noisxxnotyynotxisi";

    public static int count(String str) {
        int count = 0;
        int index = -1;

        //if (STR.lastIndexOf(str) == -1) {
        //  return count;
        //}

        while ((index = STR.indexOf(str, index + 1)) != -1) {
            count++;
        }

        return count;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(Test.count("is"));
        System.out.println(Test.count("no"));
    }
}

1 Comment

str will be the sub-string, right? How should I use loop with it? should I use a counter and another variable and chack if the string.index equales to the value?
0

You can do this, but a loop would be faster.

String text = "noisxxnotyynotxisinono";
String search = "no";
int count = text.split(search,-1).length-1;

System.out.println(Arrays.toString(text.split(search,-1)));
System.out.println("count= " + count);

prints

[, isxx, tyy, txisi, , ]
count= 5

As you can see this is correct if the text starts or ends with the search value. The -1 argument stops it removing trailing seperators.

You can use a loop with indexOf() which is more efficient, but not as simple.

BTW: Java 5.0 has been EOL since Aug 2007. Perhaps its is time to look at Java 6. (though the docs are very similar)

8 Comments

"Java SE 5.0 is in its Java Technology End of Life (EOL) transition period. The EOL transition period began April 8th, 2007 and will complete October 8th, 2009, when Java SE 5.0 will have reached its End of Service Life (EOSL)"
@The End Of Life. As in "not officially or unofficially supported by anyone on any level".
@The Elite Gentleman "End Of Life". Means you shouldn't start any new projects in it, and should move away from it in your current projects.
@Peter: Check out one two one and split for one: You get a two-element array: {'', ' two '}. Now your count is 1 although 'one' appears two times in the text.
@theomega, If you meant there is a problem with trailing seperators, I have fixed that now. ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.