【问题标题】:Comparing a string with an array list to see if the string contains anything from the list将字符串与数组列表进行比较以查看字符串是否包含列表中的任何内容
【发布时间】:2016-08-29 02:52:59
【问题描述】:

我有一个区域,当提交字符串时,我想检查该字符串是否包含来自 arrayList 的任何内容。例如,在arrayList 中,我可能有字符串"visit""enter"。用户可以输入类似"enter village""visit cave" 的内容。我只是希望能够将字符串与 arrayList 进行比较以检测任何关键字。如果它有来自列表的关键字,它可以采取相应的行动。我现在的代码如下所示:

if(enterList.contains(text)) //code goes here;

text 是用户输入的字符串。但是这种工作方式与我想要的相反。它查看enterList 是否包含text,而不是text 是否包含来自enterList 的任何内容。有没有办法查看字符串中的任何内容是否包含列表中的任何内容?

【问题讨论】:

  • 文本包含来自 enterList 的任何内容是什么意思?
  • 试试for循环:for (String word : enterList) if (text.contains(word)) return true; return false;
  • @ShreyosAdikari 我的意思是我想看看 arrayList 中的任何内容是否在名为 text 的字符串中。因此,即使字符串是“visit village”并且arrayList 只包含一个等于“visit”的字符串,它也会检测到该文本包含列表中的某些内容。
  • @TechBandit 知道了。然后你必须像 Andreas 所说的那样使用 for 循环。

标签: java arrays string arraylist contains


【解决方案1】:

以下代码还可以让您获得存在的令牌,而不是简单地了解它们是否存在。

List<String> listWords; // List of Words against which checking will happen
String sentence; // Concerned String to check

...

Stream.of(sentence.split("[ |.]"))
      .filter(token -> listWords.contains(token))
      .forEach(System.out::println);

上面只是打印遇到的令牌。您可以按如下方式更改代码以添加更多逻辑。

Stream.of(sentence.split("[ |.]"))
      .filter(token -> listWords.contains(token))
      .forEach(f -> {
          // Your logic here
      });

【讨论】:

    【解决方案2】:

    请尝试这个首先将您的字符串按空格拆分为数组,然后将数组与您的列表进行比较

    String[] splited = text.split("\\s+");
    if(Collections.disjoint(yourArray, Arrays.asList(splited ))){
    //your logic
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多