java - 在数组列表的条目中搜索一段文本的最简单方法?

标签 java search arraylist

我有一个包含(比方说)三个条目的数组列表。

The first entry: "Chris lives at 2320 alpha street"
The second entry: "Bob sleeps at 1900 bravo road"
The third entry: "Alex eats at 4231 charlie lane"

I'm trying to search through the arraylist, parse each line for a term the user enters, and return (to another part of my code) the index of the arraylist entry that contains the search term. In this example, the user types in "lane", the code searches all three, finds that the third entry contains the word "lane", and then returns a 2.

Currently, I'm using

if(addressBook.contains(searchModifier))//if their searchModifier is found anywhere in any of the strings
    return addressBook.indexOf(searchModifier);//return that index value
else
    return noEntry;

但这仅在存在完全匹配的字符串时才有效。我需要能够仅搜索字符串的一部分。有没有一种简单的方法可以做到这一点?我检查了this question ,但对于我想要做的事情来说,这似乎非常复杂 - 这是一个“hello world”类型的程序。我最多只搜索 3-4 个条目! (更不用说我对此还很陌生,而且代码看起来非常先进......)

最佳答案

for (int i = 0; i < addressBook.size(); i++) {
  if (addressBook.get(i).contains(searchModified)) {
    return i;
  }
}

https://coderpad.io/279611

关于java - 在数组列表的条目中搜索一段文本的最简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751383/

相关文章:

arrays - 不按顺序搜索 MongoDB 数组

比较单词的算法(不按字母顺序)

java - 如何克隆()StringBuilder

java - 将 2 个数组列表添加到 1 个具有相同索引值的数组列表中

java - 如何切换对象字段的数据类型?

java - 如何重写父类的方法但允许可选参数?

java - 如何将 Spring security 与自定义 java 类/自定义 spring 框架的类一起使用?

java - Foreach 在循环的特定部分

search - Javamail使用关键字搜索未读邮件(多个搜索词)

java - 如何打印由用户指定行数的整数三角形?