废话少说,直接上代码。
public class Test {
public static void main(String[] args) {
Test test = new Test();
int[] temp = test.checkLetters("dagaerdfgirhfgsd");
for (int i = 0; i < temp.length; i++) {
if (temp[i] == 0) continue; // 不遍历出现数量为0的字母。
System.out.println((char) ('a' + i) + ":" + temp[i]);
}
}
/**
* 检查给定的字符串所含的字母数量。
*
* @param str 需要检查的字符串。
* @return 对应26字母的整型数组。其元素为对应字母的数量。
*/
public int[] checkLetters(String str) {
int[] temp = new int[26];
for (int i = 0; i < str.length(); i++) {
if ('a' <= str.charAt(i) && str.charAt(i) <= 'z') {
temp[str.charAt(i) - 'a']++;
}
}
return temp;
}
}