Java如何计算字符串中char出现的次数?

本示例说明如何计算字符串中字符出现的次数。我们展示了两种方法,使用String.replaceAll(String regex, String replace)方法和创建一个循环,以检查String中的每个字符并计算匹配的字符。

package org.nhooo.example.lang;

public class CharCounter {
    public static void main(String[] args) {
        String text = "a,b,c,c,e,f,g,g,g,g,h";

        // 使用CharCounter.countCharOccurrences()方法进行计数。
        int numberOfLetterC = CharCounter.countCharOccurrences(text, 'c');
        System.out.println("Letter c = " + numberOfLetterC);

        //其他解决方案是使用String.replaceAll()方法。
        // 我们将用空字符串替换除计数字符以外的其他字符。
        // 为了得到出现的字符,我们计算剩余的长度
        // 字符串。
        int numberOfComma = text.replaceAll("[^,]", "").length();
        System.out.println("Comma    = " + numberOfComma);

        int numberOfLetterG = text.replaceAll("[^g]", "").length();
        System.out.println("Letter g = " + numberOfLetterG);
    }

    /**
     * 计算指定字符在字符串中出现的次数。
     */
    private static int countCharOccurrences(String source, char target) {
        int counter = 0;

        // 循环遍历字符串,如果
        // 在字符串中找到目标字符。 
        for (int i = 0; i < source.length(); i++) {
            if (source.charAt(i) == target) {
                counter++;
            }
        }
        return counter;
    }
}