Java Char Count countChars(final String str, final char chr)

Here you can find the source of countChars(final String str, final char chr)

Description

Counts the number of occurrences of a character in a string.

License

Open Source License

Parameter

Parameter Description
str the string to check
chr the character to count

Return

the number of matching characters in the string

Declaration

public static int countChars(final String str, final char chr) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from w ww .j  av  a2 s.  co  m
     * Counts the number of occurrences of a character in a string.
     * <p/>
     * Does not count chars enclosed in single or double quotes
     *
     * @param str the string to check
     * @param chr the character to count
     * @return the number of matching characters in the string
     */
    public static int countChars(final String str, final char chr) {
        int count = 0;
        boolean isWithinDoubleQuotes = false;
        boolean isWithinQuotes = false;

        for (int i = 0; i < str.length(); i++) {
            final char c = str.charAt(i);
            if (c == '"' && !isWithinQuotes && !isWithinDoubleQuotes) {
                isWithinDoubleQuotes = true;
            } else if (c == '"' && !isWithinQuotes) {
                isWithinDoubleQuotes = false;
            }

            if (c == '\'' && !isWithinQuotes && !isWithinDoubleQuotes) {
                isWithinQuotes = true;
            } else if (c == '\'' && !isWithinDoubleQuotes) {
                isWithinQuotes = false;
            }

            if (!isWithinDoubleQuotes && !isWithinQuotes) {
                if (chr == c) {
                    count++;
                }
            }
        }
        return count;
    }
}

Related

  1. countCharacters(String code, char c, int start, int end)
  2. countCharacters(String str, char chr)
  3. countCharInString(String s, char c)
  4. countChars( final String testString, final char match )
  5. countChars(final String str, final char c)
  6. countChars(final String string, final String findStr)