Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains all strings from array

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");   
    }
}
like image 707
Zwedgy Avatar asked Dec 10 '22 11:12

Zwedgy


2 Answers

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;
}
like image 148
Andremoniy Avatar answered Dec 26 '22 21:12

Andremoniy


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");
}
like image 27
Elliott Frisch Avatar answered Dec 26 '22 20:12

Elliott Frisch