思路:
-
声明一个map集合key来存储字符,value用来存储出现的次数
-
获得一个字符串
-
将字符串转化为char数组
-
利用ASCII码表的范围,设置map的key为各字符,value统一设置为0
-
如果该字符串的值与已设置的key相等,则对应的value值+1
-
将出现大于0的字符和次数输出
代码如下
package 集合练习题;
import utils.RandomUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
//统计一个字符串包含哪些字符和出现的次数
public class StatisticalCharacterNumber {
public static void main(String[] args) {
//声明一个map集合key来存储字符,value用来存储出现的次数
Map<Character,Integer> map=new HashMap<>();
String s ="sjhdjshdJKKJIHSDJI::;'sd,,q1@@#$.llll";
//获得一个随机字符串(暂时不包括其他符号,可自行设置)
// String s= RandomUtils.randomString(26);
System.out.println(s);
//将字符串转化为char数组
char[] chars = s.toCharArray();
//利用ASCII码表的范围,设置map的key为各字符,value统一设置为0
for (int i = 0; i <=127 ; i++) {
map.put((char) i,0);
}
for (int i = 0; i <chars.length ; i++) {
//如果该字符串的值与已设置的key相等,则对应的value值+1
if (map.containsKey(chars[i])){
map.put(chars[i],map.get(chars[i])+1);
}
}
Set<Map.Entry<Character, Integer>> entries = map.entrySet();
//将出现大于0的字符和次数输出
entries.forEach(e-> {if(e.getValue()!=0)
System.out.println(e.getKey()+"出现的次数:"+e.getValue());
});
}
}