【问题标题】:how to get the index for first occurence of any word from arraylist in sentence如何从句子中的arraylist中获取任何单词第一次出现的索引
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    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),因此找不到“软件”。或者进行不区分大小写的搜索。

    【讨论】:

    • "软件" ?那是哪里?
    • @AdriaanKoster 在搜索“are”时也会找到“software”。
    【解决方案3】:

    您可能需要将字符串拆分为单词列表。

    如果只使用containsindexOf,可能会给出错误的答案。比如……

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

    【讨论】:

      【解决方案4】:

      您可以使用String.indexOf 方法。但请注意,索引从 0 开始,因此在您的示例中,输出将为 4。

      【讨论】:

        【解决方案5】:

        可能是这样的:

        int firstIndex = Integer.MAX_VALUE;
        for(String word : search) {
          int foundIndex = sentence.indexOf(word);
          if(foundIndex != -1 && foundIndex < firstIndex){
            firstIndex = foundIndex;
          }
        }
        
        if(firstIndex != Integer.MAX_VALUE){
          System.out.println("Found index is: " + firstIndex);
        } else{
          System.out.println("None of the words were found in the sentence.");
        }
        

        如果找不到单词.indexOf 将返回-1。如果找到,我们将最低的保存在firstIndex-变量中。

        Try it online.

        【讨论】:

          猜你喜欢
          • 2020-04-29
          • 2023-01-23
          • 1970-01-01
          • 2014-12-21
          • 2012-04-17
          • 2011-01-29
          • 1970-01-01
          • 2014-07-15
          • 2012-01-06
          相关资源
          最近更新 更多