欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

统计字符串和每个字符串出现的次数

程序员文章站 2022-04-30 20:41:42
...

统计字符串和每个字符串出现的次数

public class HashMapDemo2 {
    public static void main(String[] args) {
        System.out.println("请输入任一字符如abcd等多次");
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        HashMap<Character, Integer> hm = new HashMap<>();
        for (int i = 0; i < line.length(); i++){
            char key = line.charAt(i);
            Integer value = hm.get(key);
 //当遍历输入的字符第一次出现时,集合内还没存储此键值对,value=hm.get(key)就为null,所以设定 hm.put(key,1);
            if (value == null){
                hm.put(key,1);
            }else{
                value++;
                hm.put(key,value);
            }
        }
        //遍历集合,对键和值进行操作达到输出效果
        StringBuilder sb = new StringBuilder();
        Set<Character> keySet = hm.keySet();
        for (Character key : keySet){
            Integer value = hm.get(key);
            sb.append(key).append("(").append(value).append(")");
        }
        String result = sb.toString();
        System.out.println(result);
    }
}

下面是用TreeMap集合遍历,可以确保字符按顺序输出

public class TreeMapDemo2 {
    public static void main(String[] args) {
        System.out.println("请输入任一字符如abcd等多次");
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        TreeMap<Character, Integer> treeMap = new TreeMap<>();
        for (int i = 0; i < line.length(); i++){
            char key = line.charAt(i);
            Integer value = treeMap.get(key);
            //当遍历输入的字符第一次出现时,集合内还没存储成功此键值对,value=treeMap.get(key)就为null,
            // 所以设定treeMap.put(key,1),否则会出现NullPointerException空指针异常
            if (value == null){
                treeMap.put(key,1);
            }else{
                value++;
                treeMap.put(key,value);
            }
        }
        //遍历集合,对键和值进行操作达到输出效果
        StringBuilder sb = new StringBuilder();
        Set<Character> keySet = treeMap.keySet();
        for (Character key : keySet){
            Integer value = treeMap.get(key);
            sb.append(key).append("(").append(value).append(")");
        }
        String result = sb.toString();
        System.out.println(result);
    }
}