统计一段文章中每个单词出现的次数,不考虑标点符号
例如:String speak = “this is a book this is an elephont”;
(代码实现)
关于#java Map#的问题
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
关注用HashMap实现
可以参考一下这个import java.util.*; public class WordCount { public static void main(String[] args) { String speak = "this is a book this is an elephant"; // 将字符串按照空格分割成数组 String[] words = speak.split(" "); // 创建HashMap用于存储单词出现的次数 HashMap<String, Integer> map = new HashMap<>(); // 遍历单词数组,统计每个单词出现的次数 for (String word : words) { // 去除单词中的标点符号 word = word.replaceAll("[^a-zA-Z0-9]", ""); if (word.length() > 0) { // 忽略空字符串 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()); } } }本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录