java 计算一段字符串中每个单词的数量

package home;

import java.util.HashMap;
import java.util.Map;

public class WordCount {
    public static void main(String[] args) {
        String str ="hello everyone,I'm a freshman.hello freshman,welcome to our class.everyone is perfect.";
        str=str.replace(","," ").replace("."," ");
        String[] strings = str.split(" ");
        Map<String,Integer>map = new HashMap<String, Integer>();
        String word = null;
        for (String temp:strings){
            word = temp.trim();
            if (map.containsKey(word)){
                map.put(word,map.get(word)+1);
            }else {
                map.put(word,1);
            }
        }
        for (Map.Entry<String,Integer>entry:map.entrySet()){
            System.out.println(entry.getKey()+" "+entry.getValue());
        }
    }
}

输出结果
在这里插入图片描述

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页