必须得到字符串ArrayList中的字母数

Ale*_*x S 4 java arraylist

如果我给出的字符串的ArrayList,即{"hello", "goodbye", "morning", "night"},我该如何检查有多少a的,b的,c的,等有列表中?

该方法必须返回一个ints 数组,其中position [0]是a's 的数字等.例如returnArray[1] = 1,因为b列表中有一个.有没有比仅仅硬编码每个字母更好的方法呢?

public static int[] getLetters( ArrayList<String> list) {
    int [] result = new int[25];
    if(list.contains('a')) {
        result[0] = result[0] + 1;
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

有没有比再重复上述策略25次更好的方法?

Mad*_*mer 8

您可以使用它char作为一种方法来处理数组,例如......

ArrayList<String> list = new ArrayList<>(Arrays.asList(new String[]{"hello", "goodbye", "morning", "night"}));
int[] results = new int[26];
for (String value : list) {
    for (char c : value.toCharArray()) {
         // 'a' is the lowest range (0), but the ascii for 'a' is 97
        results[c - 'a'] += 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

结果导致......

[0, 1, 0, 1, 2, 0, 3, 2, 2, 0, 0, 2, 1, 3, 4, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0]
Run Code Online (Sandbox Code Playgroud)

nb:这只适用于小写字符,如果你有任何大写字符,你会得到一个数组越界错误.你可以为每个角色放置范围检查,以确保它在a和之间z,但这取决于你