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.
This question is related to
java
string
if-statement
When you say you tried to use OR, how exactly did you try and use it? In your case, what you will need to do would be something like so:
String newStr4 = strr.split("2012")[0];
if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues")...)
str4.add(newStr4);
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",...)
Of course, be mindful that your program will only be useful in english speaking countries if you detect dates this way. You might want to consider:
Set<String> dayNames = Calendar.getInstance()
.getDisplayNames(Calendar.DAY_OF_WEEK,
Calendar.SHORT,
Locale.getDefault())
.keySet();
From there you can use .startsWith or .matches or whatever other method that others have mentioned above. This way you get the default locale for the jvm. You could always pass in the locale (and maybe default it to the system locale if it's null) as well to be more robust.
A simple solution is:
if (newStr4.startsWith("Mon") || newStr4.startsWith("Tue") || newStr4.startsWith("Wed"))
// ... you get the idea ...
A fancier 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)) {
// ...
}
No one mentioned Stream
so far, so here it is:
if (Stream.of("Mon", "Tues", "Wed", "Thurs", "Fri").anyMatch(s -> newStr4.startsWith(s)))
if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || newStr4.startsWith("Weds") .. etc)
You need to include the whole str.startsWith(otherStr)
for each item, since ||
only works with boolean expressions (true or false).
There are other options if you have a lot of things to check, like regular expressions, but they tend to be slower and more complicated regular expressions are generally harder to read.
An example regular expression for detecting day name abbreviations would be:
if(Pattern.matches("Mon|Tues|Wed|Thurs|Fri", stringToCheck)) {
Source: Stackoverflow.com