0); Console.WriteLine('~'.CompareTo('a') > 0); ...">

The weird thing about string comparisons

This code:

        Console.WriteLine("~".CompareTo("a") > 0);
        Console.WriteLine('~'.CompareTo('a') > 0);

Gives me:

False
True

WTF?

+3
source share
4 answers

Another way to show this:

Console.WriteLine("a".CompareTo("b")); // -1 
Console.WriteLine("b".CompareTo("a")); // 1
Console.WriteLine('a'.CompareTo('b')); // -1 
Console.WriteLine('b'.CompareTo('a')); // 1

Console.WriteLine("~".CompareTo("a")); // -1
Console.WriteLine("a".CompareTo("~")); // 1
Console.WriteLine('~'.CompareTo('a')); // 29
Console.WriteLine('a'.CompareTo('~')); // -29

The difference may be subtle, but it is documented . Comparison in Char.CompareTo(Char)is

based on the encoded values ​​of this instance and value, not their lexicographic characteristics .

At the same time, the documentation forString.CompareTo(String)

performs a word (case sensitive and culture sensitive) comparison using current culture .

.. , (, ).

+4

myChar.CompareTo(otherChar) unicode.

myString.CompareTo(otherString) , .

+8

, myString.CompareTo(otherString) , CultureInfo.CurrentCulture.CompareInfo.Compare(myString,otherString,CompareOptions.None), .. .

, '~' 'a'.

'char.CompareTo(otherChar) ` , unicode (.. 97 ' a ' 126 ' ~ ') , , .

+2

To compare strings in the same way as characters (in order of character code only), you should use ordinal comparison:

Console.WriteLine(String.Compare("~", "a", StringComparison.Ordinal) > 0);

Conclusion:

True
+1
source

Source: https://habr.com/ru/post/1773387/


All Articles