使用HashMap统计字符串中字符出现的次数
思路:
输入一个字符串
将字符串转换成字符数组
创建HashMap对象
使用for循环,将值存入集合中
输出结果
具体代码注释如下:
//统计字符串中每个字符出现的次数
public class Test04 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//输入字符串
System.out.println("请输入一个字符串:");
String str = sc.nextLine();
//创建HashMap对象
HashMap<Character,Integer> map = new HashMap<>();
//将字符串转换成字符数组
char a[] = str.toCharArray();
//使用for循环将字符统计结果存入集合
for (int i = 0; i < a.length; i++) {
//此处的 key即是字符,也是集合中的元素
char key = a[i];
//判断该字符是否是第一次出现,即该字符是否存在,存在,则更新value的值,继续存入key
if (map.containsKey(key)){
Integer value = map.get(key);
value++;
map.put(key,value);
}
//不存在,直接存入
else {
map.put(key,1);
}
}
//使用entrySet方法遍历集合
Set<Map.Entry<Character, Integer>> entries = map.entrySet();
for (Map.Entry<Character, Integer> entry : entries) {
Character key = entry.getKey();
Integer value = entry.getValue();
System.out.println("字符"+key+"出现了"+value+"次");
}
}
}