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

Java如何查找字符串中指定关键词后面紧跟的单词

核心功能实现方案

原有代码问题修正

首先修复现有框架里的基础错误:

  • String类是不可变类型,toLowerCase()方法会返回转换后的新字符串,直接调用不接收返回值不会修改原变量值
  • 硬编码写死的substring(5,8)只能适配固定位置的文本,无法通用匹配所有关键词位置
  • 缺少链式迭代、频次统计、平局判定的完整逻辑

「查找关键词后紧跟单词」核心实现逻辑

  • 第一步:将预处理后的输入文本按空格分割为有序单词数组,避免逐字符匹配的位置计算问题
  • 第二步:遍历单词数组,匹配到和当前关键词相等的元素时,校验下一位索引不越界后,取出下一位元素作为后接单词
  • 第三步:用哈希表统计所有后接单词的出现频次,遍历统计结果筛选最高频单词:
    • 若存在多个单词并列最高频,终止流程
    • 若仅存在一个最高频单词,将该单词设为新关键词,拼接结果链后重复匹配流程

完整可运行代码

package main;

import java.util.*;

public class DeepWriterMain {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("text:");
        String input = scanner.nextLine().trim().toLowerCase();
        System.out.println("starting word:");
        String currentKey = scanner.nextLine().trim().toLowerCase();
        scanner.close();

        // 按空格拆分单词,过滤连续空格产生的空字符串
        List<String> words = new ArrayList<>();
        for (String word : input.split(" ")) {
            if (!word.isEmpty()) {
                words.add(word);
            }
        }

        // 校验起始词是否存在
        if (!words.contains(currentKey)) {
            System.out.println("System has run into a problem");
            return;
        }

        StringBuilder resultChain = new StringBuilder(currentKey);

        while (true) {
            Map<String, Integer> countMap = new HashMap<>();
            // 遍历找所有当前关键词的后接单词
            for (int i = 0; i < words.size() - 1; i++) {
                if (words.get(i).equals(currentKey)) {
                    String nextWord = words.get(i + 1);
                    countMap.put(nextWord, countMap.getOrDefault(nextWord, 0) + 1);
                }
            }

            // 没有后接单词直接终止
            if (countMap.isEmpty()) {
                break;
            }

            // 找最高频单词,同时统计平局情况
            int maxCount = -1;
            List<String> maxWords = new ArrayList<>();
            for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
                int cnt = entry.getValue();
                String word = entry.getKey();
                if (cnt > maxCount) {
                    maxCount = cnt;
                    maxWords.clear();
                    maxWords.add(word);
                } else if (cnt == maxCount) {
                    maxWords.add(word);
                }
            }

            // 多个最高频则判定平局,拼接后终止
            if (maxWords.size() > 1) {
                resultChain.append(" ");
                resultChain.append(String.join("/", maxWords));
                break;
            }

            // 单个最高频,更新关键词、拼接结果,进入下一轮匹配
            String nextKey = maxWords.get(0);
            resultChain.append(" ").append(nextKey);
            currentKey = nextKey;
        }

        System.out.println(resultChain);
    }
}

示例运行效果

输入文本:hello i am john who are you oh so i see you are also john i am happy
输入起始词:i
最终输出:i am john/happy,完全匹配需求逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 08:27:42