计算每个角色

时间:2017-11-14 02:37:25

标签: java arrays string char

我试图计算字符串中的每个char,例如:

示例输入:abababx

示例输出:

a appears 3 times
b appears 3 times
x appears 1 time

以下是我所做的:

 String s = input.nextLine();

    //Invoke the count method to count each letter
    int[] counts = countLetters(s.toLowerCase());

    for (int i = 0; i < counts.length; i++) {
        if (counts[i] != 0)
            System.out.println((char)('a' - i) + " appears " +
            counts[i] + ((counts[i] == 1 ? " time" : " times")));
    }


private static int[] countLetters(String s) {
    int[] counts = new int[26];

    for (int i = 0; i < s.length(); i++) {
        if (Character.isLetter(s.charAt(i)))
            counts[s.charAt(i) - 'a']++;
    }

    return counts;
}

我得到了:

 a appears 3 times
` appears 3 times
J appears 1 time

0 个答案:

没有答案