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

Java函数开发:查找指定单词后首个目标单词的索引

解决Java函数查找指定单词后首个目标单词索引的问题

你当前的代码逻辑完全搞反了——你先找nextWord的位置,再在它后面找word,这和需求要求的**找到word之后的首个nextWord**完全相反,这就是测试用例返回错误结果的原因。

正确实现思路

  1. 先定位word第一次出现的位置(忽略大小写)
  2. 如果找不到word,直接返回-1
  3. 从word结束的位置(即word的索引 + word的长度)开始,查找nextWord第一次出现的位置(忽略大小写)
  4. 返回该位置,找不到则返回-1

修正后的代码

import org.apache.commons.lang3.StringUtils;

public class StringSearchUtil {
    public static int indexOfPreceded(String str, String word, String nextWord) {
        // 查找word首次出现的位置(忽略大小写)
        int wordIndex = StringUtils.indexOfIgnoreCase(str, word);
        if (wordIndex == -1) {
            return -1;
        }
        // 从word结束的位置开始查找nextWord
        return StringUtils.indexOfIgnoreCase(str, nextWord, wordIndex + word.length());
    }
}

测试验证

错误场景验证

针对你提到的测试字符串:

String s =  "Hatred was spreading everywhere, blood was being spilled everywhere, wars were breaking out everywhere dinosaurs are everywhere, but please note I want the first and index.";

传入word = "and",nextWord = "everywhere"时:

  • 找到"and"的位置为158
  • 从158 + 3 = 161的位置开始查找"everywhere",后续无匹配,返回-1,符合预期。

正确场景验证

针对第一个示例字符串:

String s = "Hatred was spreading everywhere, blood was being spilled everywhere, wars were breaking out everywhere      and dinosaurs are everywhere, but please note I want the first and index.";

传入word = "everywhere",nextWord = "and"时:

  • 首次找到"everywhere"的位置为27
  • 从27 + 11 = 38的位置开始查找"and",返回其首次出现的索引,符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 16:24:56