I want to see if multiple words found inside the string. With O(n^2) complexity. For example: sunshine - sun, shine, hine. And will print collection of strings: sun shine and hine if it matches. How do I check if a string contains a matching words?
//String search = sunshine
public static boolean wordsInsideTheString(String search) {
String[] word = {"sun", "shine", "hine"};
int counter = 0;
for(int i = 0; i < word.length; i++) {
String[] words = word[i].split("\\s+");
for (String check : words)
if(check.equalsIgnoreCase(search)) {
counter++;
break;
}
}
return false;
}
Calling the method with:
assert.True(wordsInsideTheString("sunshine");
If you just want to assert whether or not an input string matches a collection of words, then use String#matches
:
public static boolean wordsInsideTheString(String search) {
String[] word = {"sun", "shine", "hine"};
List<String> wordList = Arrays.asList(word);
String regex = ".*(?:" + String.join("|", wordList) + ").*";
return search.matches(regex);
}
If instead you also want to print which of the terms did match, then we need to do a bit more work. I suggest just iterating the array of word terms and again using String#matches
:
public static boolean wordsInsideTheString(String search) {
String[] words = {"sun", "shine", "hine"};
List<String> matches = new ArrayList<>();
boolean match = false;
for (String word : words) {
if (search.contains(word)) {
match = true;
matches.add(word);
}
}
System.out.println("Matching words: " + String.join(",", matches));
return match;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.