How to check if String
contains all Strings
from Array
.
My current code:
String word = "abc";
String[] keywords = {"a", "d"};
for(int i = 0; i < keywords.length; i++){
if(word.contains(keywords[i])){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
The code would look much more nicer if you wrap it into a separate method:
public static boolean containsAllWords(String word, String ...keywords) {
for (String k : keywords)
if (!word.contains(k)) return false;
return true;
}
If you are using Java 8+, you could use a Stream
and test if all of the elements match your criteria with one line. Like,
if (Stream.of(keywords).allMatch(word::contains)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
In earlier versions, or if you want to understand what the above is doing, it might look something like
boolean allMatch = true;
for (String kw : keywords) { // <-- for each kw in keywords
if (!word.contains(kw)) { // <-- if "word" doesn't contain kw
allMatch = false; // <-- set allMatch to false
break; // <-- stop checking
}
}
if (allMatch) {
System.out.println("Yes");
} else {
System.out.println("No");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With