给定字符数组元素:{'a','l','f','m','f','o','b','b','s','n'}
思路:将字母与ASCII表联系起来
步骤一:
定义方法printCount,无返回值,参数为字符数组
public static void printCount(int[] ch){}
步骤二:
1.定义一个int[]类型的数组,长度为26,对应26个英文字组。用来记录每个字母出现的次数
int count = new int[26];
2。用for循环来遍历字符数组,将每一个元素都减去97(小写字母ASCII码为97~132),count[0]~count[25]代表字母'a'~'z',用来
例如:'a'-97--->0
'b'-97--->1
一直到
'z'-97--->25
for (int i = 0; i < ch.length; i++){
count[ch[i]-97]++;
}
count数组元素值默认为0,每一次循环,得到一次元素位置,该位置++即为该字母出现过一次,为0即为未出现。
2.输出字母出现的次数,用for循环遍历count数组,循环内判断该元素是否为0,若不为0,则将该元素下标+97转换为字符,并将字母出现的次数输出。
for (int j = 0; j < count.length; j++){
if (count[j] != 0){
System.out.println((char)(j+97)"--"count[j]);
}
}
3.完整代码(自写)
public static void printCount(char[] ch){
int[] count = new int[26];
for (int i = 0; i < ch.length; i++){
count[ch[i]-97]++;
}
for (int j = 0; j < count.length; j++){
if (count[j] != 0){
System.out.println((char)(j+97)+"--"+count[j]);
}
}
}
4.答案代码
for (int i = 0; i < charArray.length; i++) {
int c = charArray[i];
count[c- 97]++;
}
for (int i = 0, ch = 97; i < count.length; i++, ch++) {
System.out.println((char) ch + "--" + count[i]);
}
}