get the Number of Times a Character Occurs In a String - Java java.lang

Java examples for java.lang:String Algorithm

Description

get the Number of Times a Character Occurs In a String

Demo Code


//package com.java2s;

public class Main {
    /**/*from   w  ww .  ja  va2  s . c  o  m*/
     * get the Number of Times a Character Occurs In a String
     * @param needle
     * @param hayStack
     * @return
     */
    public static int getNumberTimesCharacterOccursInString(char needle,
            String hayStack) {

        int numberTimes = 0;

        char[] charArray = hayStack.toCharArray();

        for (char charFromString : charArray) {
            if (charFromString == needle) {
                numberTimes++;
            }
        }

        return numberTimes;
    }
}

Related Tutorials