开发者

How to check string with array of strings in java?

开发者 https://www.devze.com 2023-03-23 19:10 出处:网络
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:

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 h开发者_如何学Celp me?

thanks in advance


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.
    } 
}


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.


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");
0

精彩评论

暂无评论...
验证码 换一张
取 消