Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 558
FredBones Avatar asked Mar 20 '12 16:03

FredBones


People also ask

How do you know if a string starts with a prefix?

To check if a String str starts with a specific prefix string prefix in Java, use String. startsWith() method. Call startsWith() method on the string str and pass the prefix string prefix as argument. If str starts with the prefix string prefix , then startsWith() method returns true.

How do you check if a string has a prefix of another?

C++ std::string Checking if a string is a prefix of another In C++14, this is easily done by std::mismatch which returns the first mismatching pair from two ranges: std::string prefix = "foo"; std::string string = "foobar"; bool isPrefix = std::mismatch(prefix. begin(), prefix.

How do you find the prefix of a string?

A prefix of a string S is any leading contiguous part of S. A suffix of the string S is any trailing contiguous part of S. For example, "c" and "cod" are prefixes, and "ty" and "ity" are suffixes of the string "codility".

How do you check a string is a prefix of another string in Python?

The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .


2 Answers

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).*")) 
like image 134
hmjd Avatar answered Sep 28 '22 08:09

hmjd


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",...) 
like image 33
Thomas Avatar answered Sep 28 '22 10:09

Thomas