双列集合和正则表达式使用的经典题目:录入字符串并且统计

/*键盘录入一个字符串,分别统计出其中英文字母、空格、数字和其它字符的数量,
输出结果:”其他=1, 空格=2, 字母=12, 数字=6”*/

核心思想:

对相同基本类型的个数统计,正则表达式的使用

单独写一个方法,对双列集合存储(经典判断三步骤);

利用双列集合,key值是String类型,value值是Integer类型记录个数

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

public class Test {

    public static void main(String[] args) {
        System.out.println("请输入一个字符串.....");
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        char[] ch = input.toCharArray();
        HashMap<String,Integer> hm = new HashMap<>();
        
        for (char c : ch) {
            if( c <= 'z' && c >='a' || c >='A' && c <='Z') {
                countingkey(hm ,"字母");
            }else if(c == ' '){
                countingkey(hm ,"空格");
            }else if('0' <= c && c <= '9'){
                countingkey(hm ,"数字");
            }else{
                countingkey(hm ,"其他");
            }
        }
        System.out.println(hm);
        //用键值对方式遍历双列数组
        Set<Entry<String,Integer>> entrys =  hm.entrySet();
        for (Entry<String, Integer> entryss : entrys) {
            if(entryss.getKey().equals(" ")) {
                hm.put("空格", entryss.getValue());
            }else if(entryss.getKey().equals(" ")) {
                
            }
        }
    }
    public static void countingkey(HashMap<String,Integer> map,String key) {
        Integer num = map.get(key);
        if(num == null) {
            map.put(key, 1);
        }else {
            map.put(key, num+1);
        }
    }
}
原文地址:https://www.cnblogs.com/YangGC/p/8586516.html