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,030
  • 21
  • 100
  • 124
PSR
  • 38,073
  • 36
  • 106
  • 149

6 Answers6

44

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

s.toLowerCase().contains("ABCD".toLowerCase());
sanbhat
  • 17,162
  • 6
  • 47
  • 63
  • 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
  • 39,719
  • 12
  • 74
  • 101
David
  • 18,969
  • 28
  • 104
  • 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,147
  • 1
  • 37
  • 50
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
  • 38,073
  • 36
  • 106
  • 149
Philip Helger
  • 1,755
  • 17
  • 28
2

You can do this with toLowerCase. Something like this:

s.toLowerCase().contains("aBcd".toLowerCase());
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Hugo Pedrosa
  • 336
  • 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,030
  • 21
  • 100
  • 124
KhAn SaAb
  • 5,175
  • 5
  • 29
  • 50