How do I search for a list of strings inside another string?

Caleigh O'Brien :

Here is some code that works, but looks inelegant. What is a better way to search for any occurrence of these strings inside another string?

String AndyDaltonInjury = "broken right thumb";

if (AndyDaltonInjury.toLowerCase().contains("broken") &&
    (AndyDaltonInjury.toLowerCase().contains("knee") ||
    AndyDaltonInjury.toLowerCase().contains("leg")   ||
    AndyDaltonInjury.toLowerCase().contains("ankle") ||
    AndyDaltonInjury.toLowerCase().contains("thumb") ||
    AndyDaltonInjury.toLowerCase().contains("wrist"))) 
{
    System.out.println("Marvin sends in the backup quarterback.");  
}
Nikolas :

Use the Set collection and its method Set::contains insde streaming the split array with the space (" ") delimiter:

Set<String> set = new HashSet<>(Arrays.asList("knee", "leg", "ankle", "thumb", "wrist"));

String lower = "broken right thumb".toLowerCase();
String split[] = lower.split(" ");
if (lower.contains("broken") && Arrays.stream(split).anyMatch(set::contains)) {
    System.out.println("Marvin sends in the backup quarterback.");
}

Moreover, I highly recommend you to use lower-cased variable names.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=85634&siteId=1