利用HashMap计算一个字符串中每个字符出现的次数

问题描述:计算一个字符串中每个字符出现的次数

问题分析:每个字符串对应着它的次数,且字符串唯一不重复,这让我们想到了HashMap中的键值对。

                  1.使用Scanner获取字符串

                  2.遍历字符串,获取每一个字符

                             (1)String类的toCharArray()方法,把字符串转换成一个字符数组,再遍历数组。

                             (2)String 类的length()方法得到长度,for循环获取第 i 个字符,charAt()方法

                  3.判断获取到的字符是否存储在Map集合中

                              (1)用Map的containsKey()方法查询是否存储在Map中:

                                       若返回true: 将对应的value值取出;value++;将新value放入Map中;

                                       若返回false: 将字符作为key, 1作为index存储到Map中。

                              (2)用Map的getKey()方法:

                                       若返回null: 则不存在;

                                       若返回非null: 则存在。

代码编写

package cn.itcast.algi1;

import java.util.HashMap;
import java.util.Scanner;


public class CalculateCharacter {
    public static void main(String[] args) {
        HashMap<Character,Integer> counts=new HashMap<>();
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入字符串");
        String str=sc.next();
        char[] chars=str.toCharArray();
        for (char c : chars) {
            if (counts.containsKey(c)) {
                //字符已经存在
                Integer val = counts.get(c);
                val++;
                //已经有key,再put则覆盖原来的value
                counts.put(c, val);
            } else {
                //字符不存在
                counts.put(c, 1);
            }
        }
        //遍历Map集合
        for(Character key:counts.keySet()){
            Integer value=counts.get(key);
            System.out.println(key+": "+value);
        }
    }
}

结果展示

原文地址:https://www.cnblogs.com/iceywu/p/12040569.html