Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check string with array of strings in java?

Tags:

java

HI I want to check one string value with an array of strings. I am using the contains() method, but it is case sensitive. For example:

String str="one";
String [] items= {"ONE","TWO","THREE"};

str.contains(items); // it is returning false.

Now the question is how to check that string ?

can anyone help me?

thanks in advance

like image 535
shiva Avatar asked Dec 22 '22 10:12

shiva


2 Answers

You probably want to know if items contain str? And be case-insensitive. So loop through the array:

boolean contains = false;
for (String item : items) {
    if (str.equalsIgnoreCase(item)) {
        contains = true;
        break; // No need to look further.
    } 
}
like image 197
Joonas Pulakka Avatar answered Dec 29 '22 00:12

Joonas Pulakka


you could sort the string first using stringArray=Arrays.sort(stringArray); you can then use the Binary Search algorithm int pos = Arrays.binarySearch(stringArray, stringItem);. if (pos > -1) then you found the element else the stringItem doesnot exist in the stringArray.

like image 26
Anantha Sharma Avatar answered Dec 29 '22 01:12

Anantha Sharma