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

Requirements

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

Demo

/*
 * Copyright (c) 2001-2002, Marco Hunsicker. All rights reserved.
 *
 * This software is distributable under the BSD license. See the terms of the
 * BSD license in the documentation provided with this software.
 *//*  w w  w . ja  v  a 2s . c  o m*/
 
//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        char character = 'a';
        char[] string = new char[] { 'b', 'o', 'o', 'k', '2', 's', '.',
                'c', 'o', 'm', 'a', '1', };
        System.out.println(occurs(character, string));
    }

    /**
     * Returns the number of occurrences of <em>character</em> in <em>string</em>.
     *
     * @param character character to search for.
     * @param string character array to search.
     *
     * @return number of occurrences of <em>character</em> in <em>string</em>. Returns
     *         <code>0</code> if no occurrences could be found.
     */
    public static int occurs(char character, char[] string) {
        int count = 0;

        for (int i = 0; i < string.length; i++) {
            if (string[i] == character) {
                count++;
            }
        }

        return count;
    }

    /**
     * Returns the number of occurrences of <em>character</em> in <em>string</em>.
     *
     * @param character character to search for.
     * @param string string to search.
     *
     * @return number of occurrences of <em>character</em> in <em>string</em>. Returns
     *         <code>0</code> if no occurrences could be found.
     */
    public static int occurs(char character, String string) {
        return occurs(character, string.toCharArray());
    }
}