Java - Write code to Return the number of occurrences of target character in the supplied string.

Requirements

Write code to Return the number of occurrences of target character in the supplied string.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        char character = 'a';
        String text = "book2s.com";
        System.out.println(countOf(character, text));
    }/*from   w w w  . j  a v  a2 s.c  o m*/

    /**
     * Return the number of occurrences of target character in the supplied string.
     * 
     * @param character
     * @param text 
     * 
     * @return Occurrence count.
     */
    public static int countOf(char character, String text) {
        int count = 0;
        int indexFrom = 0;
        int nextIndex = 0;
        while (nextIndex >= 0) {
            nextIndex = text.indexOf(character, indexFrom);
            if (nextIndex > 0) {
                count++;
            }
            // Skip past target character.
            indexFrom = nextIndex + 1;
        }

        return count;
    }
}