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.  j  a v a 2  s .  c  o m*/

    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