话不多说,上代码,
//通过treeMap
public static void getCount(String str){
if(str.length() == 0 && str == null){
return;
}
Map<Character,Integer> map = new TreeMap<Character,Integer>();
for(int i = 0;i < str.length();i++){
char c = str.charAt(i);
int count = 1;
if(map.containsKey(c)){
count = map.get(c) + 1;
}
map.put(c,count);
}
System.out.println(map);
}
第二种:
public static void getCount1(String str){
//先判断该字符串是否为空或者没有
if(str == null && str.length() == 0){
return;
}
Map<Character,Integer> map = new TreeMap<>();
for(int i = 0;i < str.length();i++){
char c = str.charAt(i);
//利用键的不重复性
Integer count = map.get(c);
//如果count为null,表示该字符是第一次出现,默认给它1
if(count == null){
count = 1;
}else{
//表示出现过了,在map中
count++;
}
map.put(c,count);
}
System.out.println(map);
}
第三种:
public static void getCount3(String str){
int[] arr = new int[123];
//先遍历字符串
for(int i = 0;i < str.length();i++){
//那就可以将每个遍历到的字符作为数组的下标,出现的个数作为它对应索引的值
int index = str.charAt(i);
arr[index]++;
}
for(int i = 0;i < arr.length;i++){
if(arr[i] != 0){
System.out.println((char)i +" "+arr[i]);
}
}
}