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

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

问题描述

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



而不是使用

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


解决方案

这里是一个(VERY BASIC)静态方法。注意,它对比较字符串区分大小写。



如果您需要做比这更复杂的事情,或者如果您担心区分大小写,我建议您查看模式 Matcher 类,并学习如何做一些正则表达式。

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


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

解决方案

Here is a (VERY BASIC) static method. Note that it is case sensitive on the comparison strings.

If you need to do anything more complicated than this, or if you are worried about case sensitivity, I would recommend looking at the Pattern and Matcher classes and learning how to do some regular expressions.

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

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

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