Java - Write code to count number Of character Occurences in a string using indexOf() and while loop

Requirements

Write code to count number Of character Occurences in a string using indexOf() and while loop

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        char c = 'o';
        String source = "book2s.com";
        System.out.println(numberOfOccurences(c, source));
    }//from   w w  w  . java2s  .c  om

    public static int numberOfOccurences(char c, String source) {

        int count = 0;
        int pos = 0;
        while ((pos = source.indexOf(c, pos)) != -1) {
            count++;
            pos++;
        }
        return count;
    }
}

Related Example