How do I make my string comparison case-insensitive?

JavaStringComparisonCase Insensitive

Java Problem Overview


I created a Java program to compare two strings:

String str = "Hello";

if (str.equals("hello")) {
    System.out.println("match");
} else {
    System.out.println("no match");
}

It's case-sensitive. How can I change it so that it's not?

Java Solutions


Solution 1 - Java

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 will > result in unsatisfactory results for certain locales. The Collator > class provides locale-sensitive comparison.

Solution 2 - Java

Solution 3 - Java

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.)

Solution 4 - Java

You have to use the compareToIgnoreCase method of the String object.

int compareValue = str1.compareToIgnoreCase(str2);

if (compareValue == 0) it means str1 equals str2.

Solution 5 - Java

import java.lang.String; //contains equalsIgnoreCase()
/*
*
*/
String s1 = "Hello";
String s2 = "hello";

if (s1.equalsIgnoreCase(s2)) {
System.out.println("hai");
} else {
System.out.println("welcome");
}

Now it will output : hai

Solution 6 - Java

In the default Java API you have:

String.CASE_INSENSITIVE_ORDER

So you do not need to rewrite a comparator if you were to use strings with Sorted data structures.

String s = "some text here";
s.equalsIgnoreCase("Some text here");

Is what you want for pure equality checks in your own code.

Just to further informations about anything pertaining to equality of Strings in Java. The hashCode() function of the java.lang.String class "is case sensitive":

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

So if you want to use an Hashtable/HashMap with Strings as keys, and have keys like "SomeKey", "SOMEKEY" and "somekey" be seen as equal, then you will have to wrap your string in another class (you cannot extend String since it is a final class). For example :

private static class HashWrap {
    private final String value;
    private final int hash;

    public String get() {
        return value;
    }

    private HashWrap(String value) {
        this.value = value;
        String lc = value.toLowerCase();
        this.hash = lc.hashCode();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o instanceof HashWrap) {
            HashWrap that = (HashWrap) o;
            return value.equalsIgnoreCase(that.value);
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return this.hash;
    }
}

and then use it as such:

HashMap<HashWrap, Object> map = new HashMap<HashWrap, Object>();

Solution 7 - Java

Solution 8 - Java

Note that you may want to do null checks on them as well prior to doing your .equals or .equalsIgnoreCase.

A null String object can not call an equals method.

ie:

public boolean areStringsSame(String str1, String str2)
{
	if (str1 == null && str2 == null)
		return true;
	if (str1 == null || str2 == null)
		return false;
	
	return str1.equalsIgnoreCase(str2);
}

Solution 9 - Java

You can use equalsIgnoreCase

Solution 10 - Java

More about string can be found in String Class and String Tutorials

Solution 11 - Java

To be nullsafe, you can use

org.apache.commons.lang.StringUtils.equalsIgnoreCase(String, String)

or

org.apache.commons.lang3.StringUtils.equalsIgnoreCase(CharSequence, CharSequence)

Solution 12 - Java

public boolean newEquals(String str1, String str2)
{
    int len = str1.length();
int len1 = str2.length();
if(len==len1)
{
    for(int i=0,j=0;i<str1.length();i++,j++)
    {
        if(str1.charAt(i)!=str2.charAt(j))
	    return false;
    }`enter code here`
}
return true;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser268018View Question on Stackoverflow
Solution 1 - JavaMichael BavinView Answer on Stackoverflow
Solution 2 - JavaThirlerView Answer on Stackoverflow
Solution 3 - JavagltsView Answer on Stackoverflow
Solution 4 - JavaAlitiView Answer on Stackoverflow
Solution 5 - JavaKNUView Answer on Stackoverflow
Solution 6 - Javale-doudeView Answer on Stackoverflow
Solution 7 - JavaMorfildurView Answer on Stackoverflow
Solution 8 - JavaVeenarMView Answer on Stackoverflow
Solution 9 - JavacodaddictView Answer on Stackoverflow
Solution 10 - JavaGopiView Answer on Stackoverflow
Solution 11 - JavabrandstaetterView Answer on Stackoverflow
Solution 12 - JavajavacoderView Answer on Stackoverflow