String contains - ignore case [duplicate]
You can use
org.apache.commons.lang3.StringUtils.containsIgnoreCase(CharSequence str,
CharSequence searchStr);
Checks if CharSequence contains a search CharSequence irrespective of case, handling null. Case-insensitivity is defined as by String.equalsIgnoreCase(String).
A null CharSequence will return false.
This one will be better than regex as regex is always expensive in terms of performance.
For official doc, refer to : StringUtils.containsIgnoreCase
Update :
If you are among the ones who
- don't want to use Apache commons library
- don't want to go with the expensive
regex/Pattern
based solutions, - don't want to create additional string object by using
toLowerCase
,
you can implement your own custom containsIgnoreCase
using java.lang.String.regionMatches
public boolean regionMatches(boolean ignoreCase,
int toffset,
String other,
int ooffset,
int len)
ignoreCase
: if true, ignores case when comparing characters.
public static boolean containsIgnoreCase(String str, String searchStr) {
if(str == null || searchStr == null) return false;
final int length = searchStr.length();
if (length == 0)
return true;
for (int i = str.length() - length; i >= 0; i--) {
if (str.regionMatches(true, i, searchStr, 0, length))
return true;
}
return false;
}
If you won't go with regex:
"ABCDEFGHIJKLMNOP".toLowerCase().contains("gHi".toLowerCase())
You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:
Pattern.compile(Pattern.quote(strptrn), Pattern.CASE_INSENSITIVE).matcher(str1).find();
Try this
public static void main(String[] args)
{
String original = "ABCDEFGHIJKLMNOPQ";
String tobeChecked = "GHi";
System.out.println(containsString(original, tobeChecked, true));
System.out.println(containsString(original, tobeChecked, false));
}
public static boolean containsString(String original, String tobeChecked, boolean caseSensitive)
{
if (caseSensitive)
{
return original.contains(tobeChecked);
}
else
{
return original.toLowerCase().contains(tobeChecked.toLowerCase());
}
}