hashmap对字符串的统计

  1. package com.heima.test;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5. import java.util.Scanner;  
  6.   
  7. import javax.swing.plaf.synth.SynthSpinnerUI;  
  8.   
  9. /** 
  10.  * @author fenuang 统计字符串中每个字符出现的次数 1,定义一个需要被统计的字符串 2,将字符串转换为字符数组 
  11.  *         3,定义双列集合,存储字符串中字符以及以及字符出现的次数 4,遍历获取每一个字符,并存储在双列集合中 
  12.  *         5,存储过程做判断,如果不包含该键,就将该字符作为键,如果包含,就将对应的键值增加一并存储 6,循环打印集合中各字符串出现的次数(键值) 
  13.  */  
  14. public class test1 {  
  15.   
  16.     public static void main(String[] args) {  
  17.         // TODO Auto-generated method stub  
  18.   
  19.         Scanner sc = new Scanner(System.in);  
  20.         System.out.println("请输入一个字符串");  
  21.         String s = sc.nextLine();  
  22.   
  23.         char[] arr = s.toCharArray();  
  24.   
  25.         HashMap<Character, Integer> map = new HashMap<>();  
  26.         for (char c : arr) {  
  27.             // if(!map.containsKey(c)){  
  28.             // map.put(c, 1);  
  29.             // }else{  
  30.             // map.put(c, map.get(c)+1);  
  31.             // }  
  32.             map.put(c, !map.containsKey(c) ? 1 : (map.get(c) + 1));  
  33.   
  34.         }  
  35.         // System.out.println(map);  
  36.         for (Character key : map.keySet()) {  
  37.             System.out.println(key + "=" + map.get(key));  
  38.         }  
  39.     }  
  40.   
  41. }  

猜你喜欢

转载自blog.csdn.net/sharehu/article/details/78170701
今日推荐