【发布时间】:2022-11-14 05:55:31
【问题描述】:
我需要在 Java 中创建一个程序,在给定的字符串中查找所有出现的 4 字母字符串,在本例中为 "lane"。
比较应该不区分大小写,并且在评估子串是否匹配时不应考虑匹配子串的第二个字母。
我当前的代码可以处理某些情况,但在其他情况下,它会返回不正确的出现次数或生成 IndexOutOfBoundsException。
我尝试了以下情况:
-
"Lanee"- 按预期返回1("Lane"匹配"lane")。 -
"LineLone"- 按预期返回2("Line"和“Lone”match“lane”`)。 -
"LLoenLL"- 产生一个IndexOutOfBoundsException。 -
"enaLLLmnee"- 返回0,但应该是1 -
"LLONElllneL"- 产生一个IndexOutOfBoundsException。我的代码:
public class Stringer { public Stringer() {} public int getOccurrences(String s) { String lower = s.toLowerCase(); int occurrences = 0; int x = 0; while (x < lower.length()) { int traverser = lower.indexOf("l", x); if (traverser != -1 && lower.length() > 3) { String sub = lower.substring(x += 2, x += 2); if (sub.equals("ne")) { occurrences++; } } else { break; } } return occurrences; } }我该如何解决这个问题?
【问题讨论】:
-
enaLLLmnee(应该为 1 时返回 0)为什么?另外,您是否也在向后寻找字符串?忽略第二个字母是什么意思?请更新您的问题以解释并提供有关
"works"含义的更多详细信息。 -
@WJS OP 意味着任何具有三个匹配字符的子字符串,除了第二个,如
"LXne",可以被视为与目标字符串"line"的有效匹配。因此,"enaLLLmnee"包含1匹配的子字符串:"Lmne"。