What is the correct way to compare char ignoring case?

前端 未结 9 2382
不知归路
不知归路 2020-12-01 20:31

I\'m wondering what the correct way to compare two characters ignoring case that will work for all cultures. Also, is Comparer.Default the best way

相关标签:
9条回答
  • 2020-12-01 21:16

    You can provide last argument as true for caseInsensetive match

    string.Compare(lowerCase, upperCase, true);
    
    0 讨论(0)
  • 2020-12-01 21:17

    string.Compare("string a","STRING A",true)

    It will work for every string

    0 讨论(0)
  • 2020-12-01 21:19

    What I was thinking that would be available within the runtime is something like the following

    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()));
    
    0 讨论(0)
提交回复
热议问题