如何正确实现前缀、后缀与中缀子串的匹配及结果区分?
问题分析与代码修正
原代码的核心问题
- Infix判断逻辑错误:直接用
contains会把前缀、后缀的情况误判为infix;同时没考虑「既是前缀/后缀、中间也存在子串」的场景(比如示例里的tattarrattat,t是前缀且中间也有t,需要同时标记prefix和infix)。 - 条件分支逻辑混乱:最后一个
else if仅和endsWith的if绑定,导致就算单词已匹配前缀/infix,只要不是后缀就会错误添加not found。 - 固定行数遍历:硬编码循环23行,字典文件行数变化时会出问题,应该动态遍历所有行。
修正后的代码
public static void substringProblem() throws FileNotFoundException { Scanner input = new Scanner(System.in); System.out.println("Enter a substring: "); String response = input.next(); Scanner inDictionary = new Scanner(DICTIONARY); // 动态遍历字典所有行,替代固定23行 while (inDictionary.hasNextLine()) { String answer = inDictionary.nextLine(); StringBuilder result = new StringBuilder(answer); boolean contains = answer.contains(response); if (!contains) { result.append(" - not found"); } else { // 判断前缀 if (answer.startsWith(response)) { result.append(" - prefix"); } // 判断后缀 if (answer.endsWith(response)) { result.append(" - suffix"); } // 判断infix:子串存在于中间,或前缀/后缀之外还有出现 boolean isInfix = false; // 情况1:既不是前缀也不是后缀,但包含子串 if (!answer.startsWith(response) && !answer.endsWith(response)) { isInfix = true; } // 情况2:是前缀,但去掉前缀后仍包含子串 else if (answer.startsWith(response)) { String remaining = answer.substring(response.length()); if (remaining.contains(response)) { isInfix = true; } } // 情况3:是后缀,但去掉后缀后仍包含子串 else if (answer.endsWith(response)) { String remaining = answer.substring(0, answer.length() - response.length()); if (remaining.contains(response)) { isInfix = true; } } if (isInfix) { result.append(" - infix"); } } System.out.println(result.toString()); } // 关闭资源 input.close(); inDictionary.close(); }
关键逻辑说明
- 动态遍历:用
while(inDictionary.hasNextLine())替代固定行数循环,适配任意行数的字典文件。 - 分层判断:
- 先判断是否包含子串,不包含直接标记
not found。 - 包含时,分别判断前缀、后缀。
- 针对infix分三种场景判断:
- 子串既不是前缀也不是后缀,直接判定为infix。
- 是前缀但去掉前缀后仍包含子串(说明中间也有),判定为infix。
- 是后缀但去掉后缀后仍包含子串(说明中间也有),判定为infix。
- 先判断是否包含子串,不包含直接标记
- 资源关闭:添加Scanner的关闭操作,避免资源泄漏。
示例验证
- 输入
t时,tattarrattat会被标记为prefix - infix(前缀且中间有t),absobloominglutely会被标记为infix(仅中间有t)。 - 输入
na时,nana会被标记为prefix - infix(前缀且中间有na),banana会被标记为infix(仅中间有na)。
内容的提问来源于stack exchange,提问作者Gauzl
相关产品推荐
相关产品推荐

