测试字符串是否包含数组中的任何字符串 [英] Test if a string contains any of the strings from an array

查看:44
本文介绍了测试字符串是否包含数组中的任何字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试字符串以查看它是否包含数组中的任何字符串?

代替使用

if (string.contains(item1) || string.contains(item2) || string.contains(item3))

解决方案

这是使用 Java 8 Streaming API 的更新.干净多了.仍然可以与正则表达式结合使用.

public static boolean stringContainsItemFromList(String inputStr, String[] items) {返回 Arrays.stream(items).anyMatch(inputStr::contains);}

此外,如果我们将输入类型更改为 List 而不是数组,我们可以使用 items.stream().anyMatch(inputStr::contains).

如果你想返回匹配的字符串,你也可以使用 .filter(inputStr::contains).findAny().

重要提示:上面的代码可以使用 parallelStream() 来完成,但大多数时候这实际上会影响性能.请参阅此问题以了解有关并行流的更多详细信息.


原答案略有过时:

这是一个(非常基本的)静态方法.请注意,比较字符串区分大小写.使其不区分大小写的原始方法是在输入和测试字符串上调用 toLowerCase()toUpperCase().>

如果您需要做比这更复杂的事情,我建议您查看 模式Matcher 类并学习如何做一些正则表达式.一旦你理解了这些,你就可以使用这些类或 String.matches() 辅助方法.

public static boolean stringContainsItemFromList(String inputStr, String[] items){for(int i =0; i < items.length; i++){if(inputStr.contains(items[i])){返回真;}}返回假;}

How do I test a string to see if it contains any of the strings from an array?

Instead of using

if (string.contains(item1) || string.contains(item2) || string.contains(item3))

解决方案

EDIT: Here is an update using the Java 8 Streaming API. So much cleaner. Can still be combined with regular expressions too.

public static boolean stringContainsItemFromList(String inputStr, String[] items) {
    return Arrays.stream(items).anyMatch(inputStr::contains);
}

Also, if we change the input type to a List instead of an array we can use items.stream().anyMatch(inputStr::contains).

You can also use .filter(inputStr::contains).findAny() if you wish to return the matching string.

Important: the above code can be done using parallelStream() but most of the time this will actually hinder performance. See this question for more details on parallel streaming.


Original slightly dated answer:

Here is a (VERY BASIC) static method. Note that it is case sensitive on the comparison strings. A primitive way to make it case insensitive would be to call toLowerCase() or toUpperCase() on both the input and test strings.

If you need to do anything more complicated than this, I would recommend looking at the Pattern and Matcher classes and learning how to do some regular expressions. Once you understand those, you can use those classes or the String.matches() helper method.

public static boolean stringContainsItemFromList(String inputStr, String[] items)
{
    for(int i =0; i < items.length; i++)
    {
        if(inputStr.contains(items[i]))
        {
            return true;
        }
    }
    return false;
}

这篇关于测试字符串是否包含数组中的任何字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆