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

I got the following if statement:

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

I want it to include startWith 'Mon' 'W' 'Weds' 'Thrus' 'Friday', etc. Is there an easy way to do this when using strings? I tried '||' but it didn’t work ...

Thank!

+94
java string expression if-statement
Mar 20 '12 at 16:11
source share
7 answers

Do you mean:

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

or you can use regex:

 if (newStr4.matches("(Mon|Tues|Wed|Thurs|Fri).*")) 
+160
Mar 20 '12 at 16:14
source share

In addition to the solutions already presented, you can use the Apache Commons Lang library:

 if(StringUtils.startsWithAny(newStr4, new String[] {"Mon","Tues",...})) { //whatever } 
+44
Mar 20 '12 at 16:22
source share

No one has mentioned Stream so far, so here:

 if (Stream.of("Mon", "Tues", "Wed", "Thurs", "Fri").anyMatch(s -> newStr4.startsWith(s))) 
+23
Mar 03 '16 at 9:47
source share

A simple solution:

 if (newStr4.startsWith("Mon") || newStr4.startsWith("Tue") || newStr4.startsWith("Wed")) // ... you get the idea ... 

The best solution would be:

 List<String> days = Arrays.asList("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"); String day = newStr4.substring(0, 3).toUpperCase(); if (days.contains(day)) { // ... } 
+7
Mar 20 '12 at 16:14
source share

Of course, remember that your program will only be useful in English-speaking countries if you find the dates this way. You might think:

 Set<String> dayNames = Calendar.getInstance() .getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()) .keySet(); 

From there you can use .startsWith or .matches or any other method mentioned above. This way you get the standard locale for jvm. You can always go to the locale (and perhaps by default use it in the system locale if it is zero) to be more reliable.

+3
Mar 20 '12 at 17:37
source share
 if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || newStr4.startsWith("Weds") .. etc) 

You need to include the whole str.startsWith(otherStr) for each element, since || only works with boolean expressions (true or false).

There are other options if you have a lot of things to check, for example regular expressions , but they are usually slower and harder expressions are usually harder to read.

An example of a regular expression to define abbreviations for the day name:

 if(Pattern.matches("Mon|Tues|Wed|Thurs|Fri", stringToCheck)) { 
+1
Mar 20 '12 at 16:14
source share

When you say you tried to use OR, how exactly did you try to use it? In your case, what you need to do would be something like this:

 String newStr4 = strr.split("2012")[0]; if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues")...) str4.add(newStr4); 
0
Mar 20 '12 at 16:14
source share



All Articles