14

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PSR
  • 39,804
  • 41
  • 111
  • 151

6 Answers6

47

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

s.toLowerCase().contains("ABCD".toLowerCase());
sanbhat
  • 17,522
  • 6
  • 48
  • 64
  • 10
    This won't necessarily work, since case convertion is locale specific. `"i".toLowerCase().contains("I".toLowerCase())` may e.g. return false. – jarnbjo May 17 '13 at 08:50
  • 1
    @jarnbjo I tested it in my location(middle east), US and English but that's not true. what location do you mean? – David Aug 29 '16 at 09:55
  • 7
    @David Any locale with deviating upper/lower-case rules won't work as expected. For Turkish, `"I".toLowerCase();` will e.g. return `"ı"` and not `"i"`. – jarnbjo Aug 29 '16 at 10:15
30

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

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

Apache documentation here

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
David
  • 19,577
  • 28
  • 108
  • 128
5

Not that it would be particularly efficient but you could use a Pattern matcher to make a case-insensitive match:

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

Also note that it won't magically solve the locale issue but it will handle it differently than toLowercase(Locale), with the conjunction of the Pattern.UNICODE_CASE flag, it may be able to handle all locales at once.

zakinster
  • 10,508
  • 1
  • 41
  • 52
3

Using "toLowercase" helps:

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

(of course you could also use toUppercase instead)

PSR
  • 39,804
  • 41
  • 111
  • 151
Philip Helger
  • 1,814
  • 18
  • 28
2

You can do this with toLowerCase. Something like this:

s.toLowerCase().contains("aBcd".toLowerCase());
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hugo Pedrosa
  • 347
  • 2
  • 12
1

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

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

It will work fine.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52