how to check whether a string contains any element specified in a set of elements? say for eg: how to check whether below statement 'I got two dogs and a cat'
contains words specified in set {dog,cat,parrot}
You can use the Pattern
and Matcher
class, constructing the regexp pattern from the values of the set, or you could loop through each value in the set and compare it to a value. Solutions are ordered from most flexible to least flexible.
Pattern p = Pattern.compile(String.join(new List<String>(keyWords),'|'));
Matcher m = p.matcher(targetString);
if(m.find()) { ... }
Boolean matches = false;
for(String key:keyWords) {
if(targetString.indexOf(key)>-1) {
matches = true;
break;
}
}
set
has not a method called containsAny
, but a string
. And containsAny
checks for any character and not for the word.
Commented
Aug 29, 2013 at 20:17
String test='There are two dogs and a cat';
set<string> a=new Set<string>{'dog','cat','pat'};
boolean check=false;
List<String> lsttest=test.split(' ');
for(String s: lsttest){
if(a.contains(s)){
check=true;
break;
}
}
system.debug('check...'+check);
You can use the above also to find whether string contains any word
The following code works pretty well without any loop :
Set<String> keyWords = new Set<String>{'dog','cat','pat'};
if(JSON.serialize(keyWords).contains('dog'))
{
System.debug('It contains dog!');
}
contains
, as it is a Set
instance method. Besides, this doesn't answer OP's question, as you are comparing to a single string only, whereas he wants to find words of that string in the set.
Commented
Aug 29, 2013 at 22:43