3 回答

TA贡献1803条经验 获得超6个赞
您可以使用String.indexOf(String)来确定子字符串的起始位置:
Integer lowestIndex = null;
for(String searchWord : search) {
int index = sentence.indexOf(searchWord);
// update the result if the searchWord occurs at a lower position
if (index >= 0 && (lowestIndex == null || lowestIndex > index)) {
lowestIndex = index;
}
}
}
if (lowestIndex == null) {
System.out.println("None of the keywords were found");
}
else {
System.out.printf("First keyword at %s%n", lowestIndex);
}

TA贡献2039条经验 获得超8个赞
Matcher m = Pattern.compile("(meet|are|rahul)").matcher(searchText);
if (m.find()) {
System.out.printf("Found '%s' at position %d%n",
m.group(), m.start());
}
如果你想从一个列表开始:
List<String> keywords = Arrays.asList("meet","are","rahul");
String pattern = keywords.stream().collect(Collectors.joining("|", "(", ")"));
正则表达式搜索速度较慢,但可以添加单词边界\\b(meet|are|rahul),因此找不到“软件”。或者进行不区分大小写的搜索。

TA贡献1868条经验 获得超4个赞
您可能需要将字符串拆分为单词列表。
如果你只使用containsor indexOf,它可能会给出错误的答案。例如...
String search = "Doctor Smith went gardening and then went to the cinema on Tuesday";
List<String> words = Arrays.asList("then", "to", "went");
如果使用,这将给出错误的答案,indexOf因为字符序列 'to' 出现在单词 'Doctor' 中。
这会匹配整个单词(区分大小写)......
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class FindWord {
public static void main(String[] args) {
String search = "Doctor Smith went gardening then went to the cinema on Tuesday";
List<String> words = Arrays.asList("then", "to", "went");
int index = 0;
int result = -1;
String match = null;
StringTokenizer tokenizer = new StringTokenizer(search, " ", true);
while(result < 0 && tokenizer.hasMoreElements()) {
String next = tokenizer.nextToken();
if(words.contains(next)) {
result = index;
match = next;
} else {
index += next.length();
}
}
if(match == null) {
System.out.println("Not found.");
} else {
System.out.println("Found '" + match + "' at index: " + result);
}
}
}
添加回答
举报