首页 > 解决方案 > 如何显示字符串中每个字母的频率?

问题描述

我希望我的代码显示每个字母的频率,但相反,我得到一个ArrayIndexOutOfBoundsException. 我很难发现我做错了什么。

我该如何纠正这个问题?

这是我的代码:

public static void solution(String s) {
    char[] c = s.toCharArray();
    int j = 0, i = 0, counter = 0;

    for(i = 0; i < c.length; i++) {
        counter = 0;
        for(j = 0; j < c.length; j++) {
            if(c[j] == c[i]) {
                counter++;
            }
        }
    }
    System.out.println("The letter " + c[j] + " appears " + counter + " times");
}

public static void main(String args[]) {
    String s = "abaababcdelkm";
    solution(s);
}

标签: javastringindexoutofboundsexceptionfrequency

解决方案


您正在完成的循环之外访问c[j]:它的值等于c.lengthwhich 不是正确的索引。

您需要将println语句上移一行并更改c[j]c[i]

我会用 Stream API 重写它:

s.chars()
 .mapToObj(c -> (char)c)
 .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
 .forEach((k, v) -> System.out.format("The letter %c appears %d times\n", k, v));

推荐阅读