Java - Write code to count string occur Times using while loop and String.indexOf()

Requirements

Write code to count string occur Times using while loop and String.indexOf()

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        String a = "book2s.com";
        System.out.println(occurTimes(string, a));
    }/* w  w w . j a  v  a  2 s .c  o m*/

    public static int occurTimes(String string, String a) {
        int pos = -2;
        int n = 0;

        while (pos != -1) {
            if (pos == -2) {
                pos = -1;
            }
            pos = string.indexOf(a, pos + 1);
            if (pos != -1) {
                n++;
            }
        }
        return n;
    }
}

Related Example