Java String Char Count countCharsInString(final String stringToCountOccurrancesIn, final char characterToCount)

Here you can find the source of countCharsInString(final String stringToCountOccurrancesIn, final char characterToCount)

Description

Count occurrances of a character in a string

License

BSD License

Parameter

Parameter Description
stringToCountOccurrancesIn <code>String</code> to count occurrances in
characterToCount <code>char</code> whose occurrances will be counted

Return

int with the count of the given character

Declaration

public static int countCharsInString(final String stringToCountOccurrancesIn, final char characterToCount) 

Method Source Code

//package com.java2s;
//License from project: BSD License 

public class Main {
    /**/* ww  w  .  ja  v a 2s  . co m*/
     * Count occurrances of a character in a string
     *
     * @param stringToCountOccurrancesIn
     *            <code>String</code> to count occurrances in
     * @param characterToCount
     *            <code>char</code> whose occurrances will be counted
     * @return <code>int</code> with the count of the given character
     */
    public static int countCharsInString(final String stringToCountOccurrancesIn, final char characterToCount) {

        if (stringToCountOccurrancesIn == null) {
            throw new IllegalArgumentException("null s");
        }

        final char[] chars = stringToCountOccurrancesIn.toCharArray();
        int count = 0;
        for (char c : chars) {
            if (c == characterToCount) {
                count++;
            }
        }
        return count;
    }
}

Related

  1. countChars(String s, char c)
  2. countChars(String s, String charset)
  3. countChars(String string, char c)
  4. countChars(String string, int character)
  5. countChars(String text, char ch, int from, int to)