How do I make my string comparison case-insensitive? How do I make my string comparison case-insensitive? java java

How do I make my string comparison case-insensitive?


The best way is to use str.equalsIgnoreCase("foo"). It's optimized specifically for this purpose.

You can also convert both strings to upper- or lowercase before comparing them with equals. This is a trick that's useful to remember for other languages which might not have an equivalent of equalsIgnoreCase.

str.toUpperCase().equals(str2.toUpperCase())

If you are using a non-Roman alphabet, take note of this part of the JavaDoc of equalsIgnoreCase which says

Note that this method does not take locale into account, and willresult in unsatisfactory results for certain locales. The Collatorclass provides locale-sensitive comparison.


String.equalsIgnoreCase is the most practical choice for naive case-insensitive string comparison.

However, it is good to be aware that this method does neither do full case folding nor decomposition and so cannot perform caseless matching as specified in the Unicode standard. In fact, the JDK APIs do not provide access to information about case folding character data, so this job is best delegated to a tried and tested third-party library.

That library is ICU, and here is how one could implement a utility for case-insensitive string comparison:

import com.ibm.icu.text.Normalizer2;// ...public static boolean equalsIgnoreCase(CharSequence s, CharSequence t) {    Normalizer2 normalizer = Normalizer2.getNFKCCasefoldInstance();    return normalizer.normalize(s).equals(normalizer.normalize(t));}
    String brook = "flu\u0308ßchen";    String BROOK = "FLÜSSCHEN";    assert equalsIgnoreCase(brook, BROOK);

Naive comparison with String.equalsIgnoreCase, or String.equals on upper- or lowercased strings will fail even this simple test.

(Do note though that the predefined case folding flavour getNFKCCasefoldInstance is locale-independent; for Turkish locales a little more work involving UCharacter.foldCase may be necessary.)