Java自定义indexOfKeyword方法返回10而非-1的原因及修复方案
问题:indexOfKeyword方法逻辑错误排查
方法需求
我正在编写一个名为indexOfKeyword的静态方法,核心逻辑是:仅当关键词作为独立单词存在(未嵌入其他单词内部)时,返回其在字符串中的索引;若关键词仅作为其他单词的子串存在,则返回-1。
测试场景与问题
场景1:关键词仅嵌入其他单词(预期输出错误)
测试代码:
String s = "She sells seashells by the seashore."; String keyword = "sea";
这里"sea"仅作为"seashells"和"seashore"的子串存在,并未独立成词,预期输出应为-1,但当前代码输出了10(即"seashells"中"sea"的起始位置)。
场景2:存在独立关键词(部分逻辑正常)
当字符串中存在独立的关键词时,比如:
String s = "Carolyn has a car that is scary fast."; String keyword = "car";
我通过判断startIdx > 0避免了匹配"Carolyn"中的"Car",此时代码能正确输出14(独立单词"car"的起始索引)。
当前完整错误代码
public class Chatter { public static int indexOfKeyword(String s, String keyword) { s = s.toLowerCase(); keyword = keyword.toLowerCase(); int startIdx = s.indexOf(keyword); while (startIdx >= 0) { String before = " ", after = " "; if (startIdx > 0) { before = s.substring(startIdx - 1, startIdx); } int endIdx = startIdx; if (endIdx < s.length()) { after = s.substring((startIdx + keyword.length()), (startIdx + keyword.length() + 1)); } if (!(before.compareTo("a") >= 0 && before.compareTo("z") <= 0 && after.compareTo("a") >= 0 && after.compareTo("z") <= 0)) { if (startIdx > 0) { return startIdx; } } startIdx = s.indexOf(keyword, s.indexOf(keyword) + 1); } return -1; } public static void main(String[] args) { // ... and test it here String s = "She sells seashells by the seashore."; String keyword = "sea"; System.out.println(indexOfKeyword(s, keyword)); } }
内容的提问来源于stack exchange,提问作者tj_3299
相关产品推荐
相关产品推荐

