I always assumed that .Net compares strings lexicographically, according to the current culture. But there is something strange when one of the strings ends on '-':
"+".CompareTo("-")
Returns: 1
"+1".CompareTo("-1")
Returns: -1
I get it an all cultures I tried, including the invariant one. Can anyone explain what is going on, and how can I get the consistent character-by-character ordering for the current locale?
The C# Compare() method is used to compare first string with second string lexicographically. It returns an integer value. If both strings are equal, it returns 0. If first string is greater than second string, it returns 1 else it returns -1.
In Java, using == or != to compare two strings for equality actually compares two objects for equality rather than their string values for equality.
In C#, Equals(String, String) is a String method. It is used to determine whether two String objects have the same value or not. Basically, it checks for equality. If both strings have the same value, it returns true otherwise returns false.
Try changing this to
string.Compare("+", "-", StringComparison.Ordinal); // == -2
string.Compare("+1", "-1", StringComparison.Ordinal); // == -2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With