忽略字母大小写情况下统计字符出现的次数

package lsh.element.algrithom;

import java.util.Scanner;

public class CountLetterIgnoreCase {
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入带有字母的字符串: ");
        String str = input.nextLine();
        int[] countLetters = countLetters(str.toLowerCase());
        for (int i = 0; i < countLetters.length; i++) {
            System.out.println((char)('a'+i)+" 出现了 "+countLetters[i]+" 次;");
        }
        input.close();
    }

    /**
     * 巧妙地利用了被处理对象内部的结构关系
     * @param str
     * @return
     */
    public static int[] countLetters(String str) {
        int[] counts = new int[26];
        for (char e : str.toCharArray()) {
            if(Character.isLetter(e)) {
                counts[e - 'a']++;
            }
        }
        return counts;
    }
    
}

 

转载于:https://www.cnblogs.com/InformationGod/p/9693463.html

你可能感兴趣的:(忽略字母大小写情况下统计字符出现的次数)