gpt4 book ai didi

java - 如何从句子中的数组列表中获取首次出现的任何单词的索引

转载 作者:行者123 更新时间:2023-12-01 17:46:23 25 4
gpt4 key购买 nike

我想从句子中获取单词的索引。但在这里我不想检查某个特定的单词。我有单词列表,我想从句子中可用的列表中获取任何单词第一次出现的索引。
我希望索引从结果索引开始获取句子的子字符串。

String sentence = "hii rahul ,nice to meet you .How are you?";
ArrayList search = new ArrayList();
search.add("are");
search.add("rahul");
search.add("meet");
for(int i=0;i<search.size();i++)
{
if (sentence.contains(search.get(i))) {
System.out.println("I found the keyword");
} else {
System.out.println("not found");
}

我尝试编写一些代码,但无法弄清楚如何获取字符串“rahul”的索引

输入:
句子:嗨拉胡尔,很高兴见到你。你好吗?
搜索词的ArrayList:["meet","are","rahul"]

预期输出:索引为 4(因为 rahul 在句子中排在第一位)

最佳答案

您可以使用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);
}

关于java - 如何从句子中的数组列表中获取首次出现的任何单词的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54710615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com