Check if a String starts with any of the given prefixes

In this post, we will check if a String starts with any of the given prefixes.

 

1. Naive

Naive approach would be to test against all possible prefixes inside a conditional statement using OR operator.

 

Download   Run Code

Output:

true

 

2. Regular expression

Another alternative is to use regular expressions for this task as demonstrated below:

 

Download   Run Code

Output:

true

 

3. Java 8 – Streams API

We can also use Streams API in Java 8 and above as shown below:

 

Download   Run Code

Output:

true

 

4. Apache Commons Lang

Finally we can use Apache Commons Lang library which has startsWithAny() method in StringUtils class.

 

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of