Search code examples
stringsubstringjava-6

Finding sub-strings in Java 6


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.


Solution

  • 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"));
        }
    }