Java-统计字符串中字母出现的次数。

废话少说,直接上代码。

public class Test {

    public static void main(String[] args) {
        Test test = new Test();

        int[] temp = test.checkLetters("dagaerdfgirhfgsd");

        for (int i = 0; i < temp.length; i++) {
            if (temp[i] == 0) continue; // 不遍历出现数量为0的字母。
            System.out.println((char) ('a' + i) + ":" + temp[i]);
        }
    }

    /**
     * 检查给定的字符串所含的字母数量。
     *
     * @param str 需要检查的字符串。
     * @return 对应26字母的整型数组。其元素为对应字母的数量。
     */
    public int[] checkLetters(String str) {
        int[] temp = new int[26];

        for (int i = 0; i < str.length(); i++) {
            if ('a' <= str.charAt(i) && str.charAt(i) <= 'z') {
                temp[str.charAt(i) - 'a']++;
            }
        }
        return temp;
    }

}
posted @ 2021-10-24 23:27  默小言  阅读(1585)  评论(0)    收藏  举报