Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison in .Net: "+" vs "-"

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?

like image 907
jmster Avatar asked Feb 11 '10 12:02

jmster


People also ask

Can we compare two strings in C#?

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.

Can you use != To compare strings?

In Java, using == or != to compare two strings for equality actually compares two objects for equality rather than their string values for equality.

How do you check if two strings are the same in C#?

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.


1 Answers

Try changing this to

string.Compare("+", "-", StringComparison.Ordinal); // == -2
string.Compare("+1", "-1", StringComparison.Ordinal); // == -2
like image 134
Anton Gogolev Avatar answered Sep 28 '22 02:09

Anton Gogolev