How to check if a string starts with one of several prefixes?

I have the following if statement:

String newStr4 = strr.split("2012")[0];
if (newStr4.startsWith("Mon")) {
    str4.add(newStr4);
}

I want it to include startsWith Mon Tues Weds Thurs Friday etc. Is there a simple way to this when using strings? I tried || but it didn't work.


Solution 1:

Do you mean this:

if (newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || ...)

Or you could use regular expression:

if (newStr4.matches("(Mon|Tues|Wed|Thurs|Fri).*"))

Solution 2:

Besides the solutions presented already, you could use the Apache Commons Lang library:

if(StringUtils.startsWithAny(newStr4, new String[] {"Mon","Tues",...})) {
  //whatever
}

Update: the introduction of varargs at some point makes the call simpler now:

StringUtils.startsWithAny(newStr4, "Mon", "Tues",...)

Solution 3:

No one mentioned Stream so far, so here it is:

if (Stream.of("Mon", "Tues", "Wed", "Thurs", "Fri").anyMatch(s -> newStr4.startsWith(s)))