Java实现:在指定单词后查找目标单词的索引(非正则)
实现无正则的指定单词后目标单词索引查找函数
给定示例字符串:
String str = "Hello all, the world is going to end here and I am the only end character which is in the end game of the end world";
我们需要写一个通用函数,参数包括完整字符串、匹配单词(比如示例中的"end")、待查找的目标单词(比如示例中的"game"),要求找到位于匹配单词之后的目标单词的起始索引,且匹配单词可在字符串中多次出现,全程不使用正则表达式。
实现思路
- 遍历字符串,逐个位置检查是否存在完整的匹配单词(避免把"ending"这类单词里的"end"误判为匹配项)
- 每找到一个合法的匹配单词,就从它结束的下一个位置开始查找目标单词
- 找到目标单词后,同样校验是否是完整单词,确保不是子串匹配
- 返回第一个符合条件的目标单词索引,未找到则返回null
Java 代码实现
public static Integer findIndexAfterMatchingWord(String fullStr, String matchingWord, String targetWord) { int matchWordLength = matchingWord.length(); int targetWordLength = targetWord.length(); int currentPosition = 0; // 循环查找所有匹配单词的位置 while (currentPosition <= fullStr.length() - matchWordLength) { // 检查当前位置是否匹配目标单词 boolean isMatch = fullStr.substring(currentPosition, currentPosition + matchWordLength).equals(matchingWord); // 检查单词边界:确保是独立单词,而非其他单词的子串 boolean isStartBoundary = currentPosition == 0 || !Character.isLetterOrDigit(fullStr.charAt(currentPosition - 1)); boolean isEndBoundary = (currentPosition + matchWordLength) == fullStr.length() || !Character.isLetterOrDigit(fullStr.charAt(currentPosition + matchWordLength)); if (isMatch && isStartBoundary && isEndBoundary) { // 从匹配单词结束的位置开始查找目标单词 int searchStartPos = currentPosition + matchWordLength; int targetPos = fullStr.indexOf(targetWord, searchStartPos); // 找到目标单词后,校验是否为独立单词 while (targetPos != -1) { boolean targetStartBoundary = targetPos == 0 || !Character.isLetterOrDigit(fullStr.charAt(targetPos - 1)); boolean targetEndBoundary = (targetPos + targetWordLength) == fullStr.length() || !Character.isLetterOrDigit(fullStr.charAt(targetPos + targetWordLength)); if (targetStartBoundary && targetEndBoundary) { return targetPos; // 返回第一个符合要求的目标单词索引 } // 若不是独立单词,继续往后查找 targetPos = fullStr.indexOf(targetWord, targetPos + targetWordLength); } } currentPosition++; } // 未找到符合条件的目标单词,返回null return null; }
代码说明
- 单词边界校验:通过判断单词前后是否为非字母数字字符(或字符串首尾),确保我们匹配的是独立单词,而非子串
- 查找逻辑:先找匹配单词,再在其后方找目标单词,保证目标单词确实位于匹配单词之后
- 灵活性:支持匹配单词多次出现的场景,会自动遍历所有匹配位置,直到找到第一个符合条件的目标单词
测试示例
调用findIndexAfterMatchingWord(str, "end", "game"),会返回示例字符串中"game"的起始索引(经计算为79)。
内容的提问来源于stack exchange,提问作者Shubham kapoor
相关产品推荐
相关产品推荐

