Tech Bandit Tech Bandit - 7 months ago 11
Java Question

Comparing a string with an array list to see if the string contains anything from the list

I have an area where a When the string is submitted, I want to check if that string contains anything from an arrayList. For example, in the arrayList I might have the strings

"visit"
and
"enter"
. The user could enter something like
"enter village"
or
"visit cave"
. I just want to be able to compare the string to the arrayList to detect for any keywords. If it has keyword from the list, it can act accordingly. The code I have right now looks like this:

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


with
text
being the string the user enters. But the way this works is the opposite of what I want. Its seeing if
enterList
contains
text
, not if
text
contains anything from
enterList
. Is there any way to see if anything in a string contains anything in a list?

Answer

please try with this First split your string by space into array and compare the array with you list like

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