【发布时间】:2019-07-09 16:09:04
【问题描述】:
我想从句子中获取单词的索引。但在这里我不想检查一个特定的词。我有单词列表,我想从句子中可用的列表中获取第一次出现的任何单词的索引。
我希望索引获取句子的子字符串,从结果索引开始。
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" 的索引。
输入:
造句:hii rahul ,nice to meet you .How are you?
检索词数组列表:["meet","are","rahul"]
预期输出:
索引为 4(因为rahul 在句子中排在第一位)
【问题讨论】:
-
Rahul 的索引 5 怎么样?此外,在您的代码中,您使用的是字符串 'hey rahul ,你好吗?' 并且在输入示例中,您提供的是 'hii rahul ,很高兴见到你。你好吗?' 也要澄清一下。
-
我认为 OP 意味着索引应该是 4,字符串 "hey rahul..." 中 "rahul" 的起始位置。 OP 可能从 1 而不是 0 开始计数...
-
所以基本上OP想要找到首先出现的搜索词的字符串中的起始位置。
-
如果不输出索引,为什么还要输出呢?仅在找到搜索词时才输出。
-
您可能无法避免使用包含,因为您想匹配整个单词。例如,如果您的句子是“The Doctor went to the shop”,其中一个搜索词是“to”,它会在“Doctor”一词中找到“to”
标签: java android string search arraylist