Java统计出现次数最多的字母及其出现的次数


/** * @author xxx */
public class GetStrCount {
    public static void main(String[] args) {
        String str = "sihdsKJKJIO76676、水电费地方 ";
        getCount(str);
    }

    private static void getCount(String str) {
        // 不区分大小写
        str = str.toLowerCase();
        str = str.replaceAll("[^a-z]", "");
        char[] arr = str.toCharArray();
        //记录26个字母的次数
        int[] counts = new int[26];

        for (int i = 0; i < arr.length; i++) {
            counts[arr[i] - 97]++;
        }

        int max = counts[0];
        for (int i = 1; i < counts.length; i++) {
            if (max < counts[i]) {
                max = counts[i];
            }
        }

        for (int i = 0; i < counts.length; i++) {
            if (counts[i] == max) {
                System.out.println(((char) (i + 97)) + "出现了" + max + "次");
            }
        }
    }
}


免责声明!

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



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