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))
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
EDIT: Here is an update using the Java 8 Streaming API. So much cleaner. Can still be combined with regular expressions too.
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()ortoUpperCase()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.