Java - Write code to Count the occurrences of character in a string.

Requirements

Write code to Count the occurrences of character in inStr.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        char character = 'o';
        String inStr = "book2s.com";
        char untilChar = '.';
        System.out.println(characterOccurs(character, inStr, untilChar));
    }// www  .jav  a 2  s  .  co  m

    /**
     * Counts the occurrences of <code>character</code> in <code>inStr</code>.
     * Starts scanning the <code>inStr</code> from the <b>end</b>. The first
     * time <code>untilChar</code> is encountered, the counting will immediately
     * stop.
     * 
     * @param character
     * @param inStr
     * @param untilChar
     * @return
     */
    public static int characterOccurs(final char character,
            final String inStr, final char untilChar) {
        int counter = 0;
        for (int i = inStr.length() - 1; i >= 0; i--) {

            final char comparChar = inStr.charAt(i);
            if (comparChar == character) {
                counter++;
            } else if (comparChar == untilChar) {
                return counter;
            }
        }
        return counter;
    }
}

Related Exercise