ChatGPT解决这个技术问题 Extra ChatGPT

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.

You mean you tried "Mon||Tues" etc.? Or did you use newStr4.startsWith("Mon")||newStr4.startsWith("Tues") ...? Either way, please define "it didn't work".
Are you trying to parse a date by any chance?? If so use SimpleDateFormat...

L
Lii

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

Is there any performance difference in the two methods you suggested?
@TheCrazyProgrammer Of course there is; matching via regular expressions is much more expensive than raw string method calls. Exact figures I cannot give, but this is the general consensus.
T
Thomas

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

d
dejvuth

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

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

great (and up-to-date) answer... btw s -> newStr4.startsWith(s) can be replaced by newStr7::startsWith to be clearer
How can I ignoreCase here ?
You can use String toLowerCase() function.
Ó
Óscar López

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

Or Arrays.binarySearch() if they search list is sorted :D
@BrendanLong a bit of an overkill for such a short list, but ok :)
M
Matt

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.


M
Muluken Getachew

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

B
Brendan Long
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)) {

G
George

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...


n
npinti

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