Here you can find the source of countChars(final String str, final char chr)
Parameter | Description |
---|---|
str | the string to check |
chr | the character to count |
public static int countChars(final String str, final char chr)
//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; } }