Sid
Sid

Reputation: 2862

Can we check if string contains in another string with case insensitive?

I want to check if string contains in another string but in case insensitive manner.

for example - "Kabir" contains in "Dr.kabir's house.". Now "Kabir" with capital K should find in "Dr.kabir's house." with or without spaces in this sentence.

I tried to use contains. But contains() is case sensitive, I also tried to use equalsIgnoreCase() but its not useful.

       for (int i = 0; i < itemsList.size(); i++) {
        if (matching.contains(itemsList.get(i))) {
            item = itemsList.get(i).trim();
            break;
        }
    }

Also tried this by making string uppercase but it checks for all the letters as Uppercase. I want to check if only initial letter is capital.

   for (int i = 0; i < itemsList.size(); i++) {
        if (matching.contains(itemsList.get(i))) {
            item = itemsList.get(i).trim();
            break;
        }
    }

Can anyone help with this please? Thank you..

EDIT : If I want to split "kabir" from the string how to do it?

Upvotes: 0

Views: 2151

Answers (3)

Scary Wombat
Scary Wombat

Reputation: 44854

make both strings lower (or upper) case

String one = "test";
String two = "TESTY";

if (two.toLowerCase ().contains (one.toLowerCase ())) {
    System.out.println ("Yep");
}
else {
    System.out.println ("Nope");
}

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522732

Just lowercase both strings and then use contains():

for (int i = 0; i < itemsList.size(); i++) {
    if (matching.toLowerCase().contains(itemsList.get(i).toLowerCase())) {
        item = itemsList.get(i).trim();
        break;
    }
}

Upvotes: 4

user3437460
user3437460

Reputation: 17474

Just convert both strings to either lower or upper case first before using .contains() method.

For example:

if (str1.toLowerCase().contains(str2.toLowerCase()))
    //do whatever

Upvotes: 3

Related Questions