What is the correct way to compare char ignoring case?

Viewed 59592

I'm wondering what the correct way to compare two characters ignoring case that will work for all cultures. Also, is Comparer<char>.Default the best way to test two characters without ignoring case? Does this work for surrogate-pairs?

EDIT: Added sample IComparer<char> implementation

If this helps anyone this is what I've decided to use

public class CaseInsensitiveCharComparer : IComparer<char> {
    private readonly System.Globalization.CultureInfo ci;
    public CaseInsensitiveCharComparer(System.Globalization.CultureInfo ci) {
        this.ci = ci;
    }
    public CaseInsensitiveCharComparer()
        : this(System.Globalization.CultureInfo.CurrentCulture) { }
    public int Compare(char x, char y) {
        return Char.ToUpper(x, ci) - Char.ToUpper(y, ci);
    }
}

// Prints 3
Console.WriteLine("This is a test".CountChars('t', new CaseInsensitiveCharComparer()));
8 Answers

I know this is an old post, but things have changed since then.

The question above can be answered by using an extension. This would extend the char.Equals to allow for locality and case insensitivity.

In an extension class, add something such as:

internal static Boolean Equals(this Char src, Char ch, StringComparison comp)
{
    Return $"{src}".Equals($"{ch}", comp);
}

I'm currently at work, so can't check this, but it should work.

Andy

You can provide last argument as true for caseInsensetive match

string.Compare(lowerCase, upperCase, true);
Related