一个字符串中可能包含a~z中的多个字符如data="yqrepoiwjafjkdayeeutkvmfdaljfaaafjdkjkdaurieworuewz" 求每个字母的出现次数,并按照出现次数从大到小打印输出
参考解答
思路:用一个长度为26的数组来对应26个不同的英文字母,初始时通过数组下标对应英文字母;因为要考虑排序,所以每个数组元素不仅要保存字符个数,还要保存英文字符
参考代码如下
import java.util.Arrays;
import java.util.Comparator;
public class Test141 {
public static void main(String[] args) {
class CharCount {
char c; // 字符
Integer count; // 字符出现的个数
public CharCount(char c, Integer count) {
super();
this.c = c;
this.count = count;
}
}
String data = "yqrepoiwjafjkdayeeutkvmfdaljfaaafjdkjkdaurieworuewz";
CharCount[] array = new CharCount[26];
for (int i = 0; i < data.length(); i++) {
char c = data.charAt(i);// 依次取出data字符串的字符
CharCount cc = array[c - 'a'];
if (cc == null) {
array[c - 'a'] = new CharCount(c, 1);
} else {
cc.count++;
}
}
Arrays.sort(array, new Comparator<CharCount>() {
@Override
public int compare(CharCount o1, CharCount o2) {
if (o1 != null && o2 != null) {
return o2.count.compareTo(o1.count);
} else {
return 0;
}
}
});
System.out.println(Arrays.toString(array));
for (CharCount cc : array) {
if (cc != null)
System.out.println("字母[" + cc.c + "]出现了[" + cc.count + "]次");
}
}
}