Java

Java - 统计字符串中每个字符出现次数

2018-01-05  本文已影响119人  533e11a308d9

利用 Map 统计字符串中每个字符出现次数

package com.code.ggsddu;
 
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
 
public class CharacterNumberByMap {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Input your string: ");
        String str = scanner.nextLine();
        Map<Object, Object> map = calculate(str);
        for (Object key : map.keySet()) {
            System.out.println("key: " + key + ", value: " + map.get(key));
        }
    }
 
    /**
     * 1.containsKey 判断 map 中是否存在该字符
     * 2.若不存在,则设该字符出现次数为 1,并将该字符(K)、重复次数(V) put 到 map
     * 3.若字符已存在,获得该字符出现次数,加 1, 并重新 put 到 map,覆盖更新
     */
    public static Map<Object, Object> calculate(String str) {
        char[] charArr = str.toCharArray();
        Map<Object, Object> map = new HashMap<>();
        for (int i = 0; i < charArr.length; i++) {
            if (!map.containsKey(charArr[i])) {
                map.put(charArr[i], 1);
            } else {
                int counts = (int) map.get(charArr[i]) + 1;
                map.put(charArr[i], counts);
            }
        }
        return map;
    }
}

 
控制台打印结果:

Input your string: java
key: a, value: 2
key: v, value: 1
key: j, value: 1
 
Process finished with exit code 0
上一篇下一篇

猜你喜欢

热点阅读