You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java查找并输出文本中所有仅出现恰好一次的单词

实现思路
  • 统计单词出现频次最便捷的方式是使用HashMap,以单词为Key,出现次数为Value存储统计结果,解决你原代码中单变量n无法存储多个单词计数的问题
  • 先遍历拆分得到的单词数组完成频次统计,再遍历统计结果筛选出出现次数恰好为1的单词输出
完整可运行代码
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class UniqueWordFinder {
    public static void main(String[] args) {
        System.out.println("Type in a sentence and click Enter:");
        Scanner scanner = new Scanner(System.in);
        String sentence = scanner.nextLine();
        // 按空格拆分句子为单词数组
        String[] words = sentence.split(" ");
        Map<String, Integer> wordCountMap = new HashMap<>();

        // 第一轮遍历:统计每个单词的出现次数
        for (String word : words) {
            // 可选优化:如果需要忽略大小写、去除标点,可以在这里处理word
            // 例:word = word.toLowerCase().replaceAll("[^a-zA-Z0-9]", "");
            if (wordCountMap.containsKey(word)) {
                // 单词已存在,次数+1
                wordCountMap.put(word, wordCountMap.get(word) + 1);
            } else {
                // 单词首次出现,次数设为1
                wordCountMap.put(word, 1);
            }
        }

        // 第二轮遍历:输出仅出现一次的单词
        System.out.println("句子中仅出现一次的单词如下:");
        for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) {
            if (entry.getValue() == 1) {
                System.out.println(entry.getKey());
            }
        }
        
        scanner.close();
    }
}
可选优化说明
  • 如果需要不区分大小写统计(比如Hello和hello算同一个单词),可以在存入Map前调用word.toLowerCase()统一转小写
  • 如果需要忽略单词前后的标点符号(比如hello,和hello算同一个单词),可以用正则replaceAll("[^a-zA-Z0-9]", "")去除非字母数字的字符

内容的提问来源于stack exchange,提问作者dimaseck05

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:54:06