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