4

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

Marnix
6,5574 gold badges47 silver badges84 bronze badges
asked Jul 30, 2011 at 8:22
1
  • I don't think you can call str.contains(items), because String.contains needs a character array, not a String array. Commented Jul 30, 2011 at 8:28

3 Answers 3

8

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.
 } 
}
answered Jul 30, 2011 at 8:27
0
2

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.

answered Jul 30, 2011 at 8:27
1

If you will only check once:

 String str="one"; String [] items= {"ONE","TWO","THREE"};
 for(String s : items){
 if(s.compareToIgnoreCase(str) == 0){
 System.out.println("match");
 }
 }

If you will do many checks:

 String str="one"; String [] items= {"ONE","TWO","THREE"};
 List<String> lowerItems = new ArrayList<String>();
 for(String s : items)
 lowerItems.add(s.toLowerCase());
 if(lowerItems.contains(str))
 System.out.println("match");
answered Jul 30, 2011 at 8:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.