Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use equalsIgnoreCase() for multiple elements in java

Tags:

java

if(string.equalsIgnoreCase("first") || 
string.equalsIgnoreCase("second") || string.equalsIgnoreCase("third"))

I need to use 10 || here (I have 10 strings to check).Is there any simple solution for this.

And i need to find which condition is satisfied.

Thanks in advance..

like image 360
PSR Avatar asked Nov 30 '22 01:11

PSR


2 Answers

You could use string.matches() which takes a regular expression into which you can coerce first, second third etc:

if (string.matches("first|second|third"))

or, for case insensitivity:

if (string.matches("(?i)first|second|third"))

Regular expressions are complex though so could be a performance issue.

like image 124
Bathsheba Avatar answered Dec 09 '22 13:12

Bathsheba


If you need to know which match is true, then use a switch (Java 7 only):

switch (string.toLowerCase())
{
    case "first": doSomething();
        break;
    case "second": ...;
        break;
    default: ...;
}
like image 31
Djon Avatar answered Dec 09 '22 14:12

Djon