FredBones
FredBones

Reputation: 1415

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.

Upvotes: 131

Views: 237214

Answers (10)

Nestor Milyaev
Nestor Milyaev

Reputation: 6595

If the task is to check if string matches any of the multiple values ignoring case, there are 2 options:

  1. Based on the answer by dejvuth, you can do a batch-checking ignoring case as follows:
    if (Stream.of("Mon", "Tues", "Wed", "Thurs", "Fri")
        .anyMatch(s -> StringUtils.startsWithIgnoreCase(newStr4, s)));
  1. Use the following method based on an implementation in StringUtils:

    public static boolean startsWithAnyIgnoreCase(
        CharSequence sequence, CharSequence... searchStrings) {
          if (!isEmpty(sequence) && !ArrayUtils.isEmpty(searchStrings)) {
            CharSequence[] searchStringsArray = searchStrings;
            int length = searchStrings.length;
    
            for (int i = 0; i < length; ++i) {
              CharSequence searchString = searchStringsArray[i];
              if (startsWithIgnoreCase(sequence, searchString)) {
                return true;
              }
            }
          }
      return false;
    }
    

Upvotes: 0

George Rappel
George Rappel

Reputation: 7198

Call stream() on the list itself if you already have a List of elements:

List<String> myItems = Arrays.asList("a", "b", "c");

Like this:

boolean result = myItems.stream().anyMatch(s -> newArg4.startsWith(s));

Instead of using Stream.of...

Upvotes: 4

Muluken Getachew
Muluken Getachew

Reputation: 1033

it is even simpler and more neat this way:

let newStr4 = strr.split("2012")[0];
if (['Mon', 'Tues', 'Weds', 'Thurs', 'Friday'].some(word => newStr4.startsWith(word))) {
    str4.add(newStr4);
}

Upvotes: 9

Thomas
Thomas

Reputation: 88707

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",...)

Upvotes: 72

hmjd
hmjd

Reputation: 121971

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).*"))

Upvotes: 212

dejvuth
dejvuth

Reputation: 7136

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

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

Upvotes: 50

Matt
Matt

Reputation: 11805

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.

Upvotes: 4

Brendan Long
Brendan Long

Reputation: 54242

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)) {

Upvotes: 1

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

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)) {
    // ...
}

Upvotes: 9

npinti
npinti

Reputation: 52185

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);

Upvotes: 0

Related Questions