zoukankan      html  css  js  c++  java
  • 统计任意字符串中字符出现次数,利用HashMap实现

    import java.util.HashMap;
    import java.util.Scanner;
    import java.util.Set;
    public class HashDemo {
    public static void main(String[] args) {
    System.out.println("请输入任意字符串:");
    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    HashMap<Character, Integer> hashMap = new HashMap<>();//创建hashmap对象
    for (int i = 0; i < s.length(); i++) {
    Character c = s.charAt(i);
    Integer value = hashMap.get(c);//判断字符串中是否存在字符c
    if (value == null) {//不存在字符c,将字符c放入hashMap中
    hashMap.put(c,1);
    }else { //存在字符,将字符个数加一,将字符c加入hashMap中
    value++;
    hashMap.put(c,value);
    }
    }
    Set<Character> set = hashMap.keySet();//遍历HashMap,利用keyset方法得到hashmap的键集合,在通过键得到对应的值(Integer类型,在这里使用时自动拆箱为int)
    for (Character n:set){
    int sum=hashMap.get(n);
    System.out.print(n+"("+sum+")");
    }

    //遍历hashmap的第二种方式,利用entrySet来得到map对象集合,在通过getKey(),getValue()方法来得到集合中存储的值
    Set<Map.Entry<Character, Integer>> entrySet = hashMap.entrySet();
    // for (Map.Entry<Character, Integer> a:entrySet){
    // Character c=a.getKey();
    // Integer sum=a.getValue();
    // System.out.print(c+"("+sum+")");
    //
    // }

    }
    }
  • 相关阅读:
    vsprintf解析
    带grub的软盘镜像制作
    SunnyOS准备4
    SunnyOS准备3
    SunnyOS准备1
    汇编第七日
    汇编第六日
    解决k8s集群中mount volume失败的问题
    更新k8s集群的证书
    为k8s集群配置自定义告警
  • 原文地址:https://www.cnblogs.com/gzy918/p/13820106.html
Copyright © 2011-2022 走看看