吃花椒的喵酱丶 2023-03-28 20:01 采纳率: 100%
浏览 26
已结题

关于#java Map#的问题

统计一段文章中每个单词出现的次数,不考虑标点符号
例如:String speak = “this is a book this is an elephont”;
(代码实现)

  • 写回答

1条回答 默认 最新

  • juechen333 后端领域优质创作者 2023-03-28 20:11
    关注

    用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());
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 4月5日
  • 已采纳回答 3月28日
  • 创建了问题 3月28日

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来