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

前端 未结 7 1111
广开言路
广开言路 2020-11-27 06:04

I have the following if statement:

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

I

相关标签:
7条回答
  • 2020-11-27 06:27

    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)) {
        // ...
    }
    
    0 讨论(0)
  • 2020-11-27 06:31

    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.

    0 讨论(0)
  • 2020-11-27 06:34

    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);
    
    0 讨论(0)
  • 2020-11-27 06:45
    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)) {
    
    0 讨论(0)
  • 2020-11-27 06:47

    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",...)
    
    0 讨论(0)
  • 2020-11-27 06:48

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

    if (Stream.of("Mon", "Tues", "Wed", "Thurs", "Fri").anyMatch(s -> newStr4.startsWith(s)))
    
    0 讨论(0)
提交回复
热议问题