In Java, how do I check if a string contains a substring (ignoring case)? [duplicate]

I have two Strings, str1 and str2. How do I check if str2 is contained within str1, ignoring case?


Solution 1:

str1.toUpperCase().contains(str2.toUpperCase())

UPD:

Original answer was using toLowerCase() method. But as some people correctly noticed, there are some exceptions in Unicode and it's better to use toUpperCase(). Because:

There are languages knowing more than one lower case variant for one upper case variant.

Solution 2:

How about matches()?

String string = "Madam, I am Adam";

// Starts with
boolean  b = string.startsWith("Mad");  // true

// Ends with
b = string.endsWith("dam");             // true

// Anywhere
b = string.indexOf("I am") >= 0;        // true

// To ignore case, regular expressions must be used

// Starts with
b = string.matches("(?i)mad.*");

// Ends with
b = string.matches("(?i).*adam");

// Anywhere
b = string.matches("(?i).*i am.*");

Solution 3:

If you are able to use org.apache.commons.lang.StringUtils, I suggest using the following:

String container = "aBcDeFg";
String content = "dE";
boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content);