Java - Write code to return the number of occurrences of a character in a string

Requirements

Write code to return the number of occurrences of a character in a string

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String s = "book2s.com";
        char ch = 'a';
        System.out.println(numMatches(s, ch));
    }//from   w w  w.  j  av  a 2 s.  c o m

    /**
     * returns the number of occurrences of a character in a string
     */
    public static int numMatches(String s, char ch) {
        if (s == null)
            return 0;

        int result = 0;
        for (int i = 0; i < s.length(); i++)
            if (s.charAt(i) == ch)
                result++;

        return result;
    }

    /**
     * returns the number of occurrences of a substring in a string
     */
    public static int numMatches(String s, String search) {
        if (s == null || search == null || "".equals(s)
                || "".equals(search))
            return 0;

        int result = 0;
        int curIndex = 0;
        while (true) {
            curIndex = s.indexOf(search, curIndex);
            if (curIndex == -1)
                break;

            curIndex++;
            result++;
        }
        return result;
    }
}