Ignore case for 'contains' for string in Java

Consider:

public static void main(String[] args) { String s = "AbcD"; System.out.println(s.contains("ABCD")); System.out.println(s.contains("AbcD")); } 

Output:

 false true 

I need the result to be true in both cases, regardless of the case. Is it possible?

+7
source share
6 answers

You need to convert both strings to the same case before using contains

 s.toLowerCase().contains("ABCD".toLowerCase()); 
+25
source

You can use org.apache.commons.lang3.StringUtils.containsIgnoreCase(String, String)

StringUtils.containsIgnoreCase(s, "ABCD") returns true

Apache documentation here

+21
source

You can use Pattern Match to make case insensitive match:

 Pattern pattern = Pattern.compile(Pattern.quote(s), Pattern.CASE_INSENSITIVE); pattern.matcher("ABCD").find(); pattern.matcher("AbcD").find(); 
+4
source

Using "toLowercase" helps:

 System.out.println(s.toLowercase(Locale.US).contains("ABCD".toLowercase (Locale.US))); 

(of course, you can also use toUppercase)

+3
source

You can do this with toLowerCase . Something like that:

 s.toLowerCase().contains("aBcd".toLowerCase()); 
+2
source

Try the following. It will return 0 if the string matches ...

 System.out.println(s.compareToIgnoreCase("aBcD")); 

It will work fine.

+1
source

All Articles