import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
单词统计
*/
public class WordCount {
public static void main(String[] args) {
System.out.println("请输入一段英文:");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
// 以空格拆分,放到数组里
String[] words = str.split(" ");
// 将字符串数组放到Map集合
Map<String, Integer> map = new HashMap<>();
for (String word : words) {
// 先判断这个单词,在不在集合里
if (map.containsKey(word)) {
// 若有,在原来的基础上加1
int nowWord = map.get(word);
map.put(word, nowWord + 1);
} else {
// 首次出现
map.put(word, 1);
}
}
System.out.println(map);
}
}
/* 运行得:
* 请输入一段英文: dog dog dog cat
*
* {cat=1, dog=3}
*
*/
统计单词个数
最新推荐文章于 2019-02-28 17:00:54 发布