在这种情况下,为什么我的Java代码输出10而不是-1,我如何修复它?



我正在创建一个静态方法,"indexOfKeyword",当字符串没有嵌入到另一个单词中时,它意味着返回一个字符串的indexOf -1,当它不发生时,它意味着返回-1。

给定

String s = "She sells seashells by the seashore.";
String keyword = "sea";

的输出应该是-1,因为关键字"sea"嵌入到每个单词中;然而,我的代码输出的却是10,这是它第一次找到"sea"在"seashells".

如果一个字符串出现了开头单独存在的情况,如

String s = "Carolyn has a car that is scary fast.";
String keyword = "car";

我设置了startIdx必须大于0的地方,以便"Car"在"Carolyn"不会被接走。当将上面的代码输入到下面的代码中时,它按预期工作,正确输出14.

下面是完整的代码,它应该输出-1:

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));
}
}

我很抱歉,也许我误解了你的意图,但是你考虑过在搜索之前用空格包装你的关键字吗?

像这样的东西应该(理论上)工作:

public static int indexOfKeyword(String s, String keyword) {
String source = s.toLowerCase();
String key = " " + keyword.toLowerCase() + " ";
return source.indexOf(key);
}

或者(正如@Tom所指出的)可以使用RegEx,但是这种解决方案更复杂,并且可能不像您希望的那样明显。

在你的例子中,它可能看起来像这样:

public static int indexOfKeyword(String s, String keyword) {
Matcher m = Pattern.compile("\s" + keyword + "\s", Pattern.CASE_INSENSITIVE).matcher(s);
return m.find() ? m.start() : -1;
}

我知道您想查找一个特定的单词,而不是一个特定的子字符串。

你的方法indexOfKeyword有两个错误。

  1. while回路状态异常。你需要把它分成两个单独的条件。
  2. 设置startIdx,为了搜索keyword的下一次出现也是错误的。

将你的代码与下面的代码比较。

public static int indexOfKeyword(String s, String keyword) {
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)) {
if (!(after.compareTo("a") >= 0 && after.compareTo("z") <= 0)) {
if (startIdx > 0) {
return startIdx;
}
}
}
startIdx = s.indexOf(keyword, startIdx + 1);
}
return -1;
}

正如@Tom在他的评论中提到的,还有其他方法可以解决这个问题。我假设你的目的是提出并实现你自己的算法,因此我向你展示了你在实现中出错的地方。

请注意,单个空格不是分隔句子中单词的唯一方法,例如,句子中的两个单词可以用逗号分隔。

最新更新