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;
    }

}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM