Search code examples
javastringcomparecontainscase-insensitive

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?


Solution

  • 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;
        }
    }