Click here to Skip to main content
15,122,845 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I tested the string.compare() and got the following results. Can anyone verify it?

'-' (dash/minus) has an ascii value of 45.
0 (zero) has ascii value of 48.
Therefore, '-' is less than any numeral digit.

Each test should return -1, but they comes out as below:
1. string.Compare("-1","2") returns -1
2. string.Compare("-2","2") returns 1
3. string.Compare("-3","2") returns 1
4. string.Compare("-1","22") returns -1
5. string.Compare("-2","22") returns -1
6. string.Compare("-3","22") returns 1

Seem like C# ignores the '-' when it compares. However, if that is true, then test #2 should return 0.
Posted

Hi,

String.Compare compares strings, not numbers. The reason you are seeing the -2 and 2 returning 1 is because the language is trying to determine where the numbers fit in terms of sorting them as words. ie if you tried to do string.Compare("-a", "a"); you will get the same result.

If comparing numbers, they should be converted to numbers. You can try to overload the Compare method and using the StringComparison.Ordinal as a third parameter and that should fix the problem.

There is more discussion on MSDN http://msdn.microsoft.com/en-us/library/system.globalization.compareoptions.aspx

Dave
   
v2
Comments
Hiren solanki 8-Oct-10 23:46pm
   
Fixed link.
Thank Dave,

If a programmer means to compare two numbers, he/she wouldn't use string.compare(). When compare 2 strings, I would expect they to be compared character by character from left to right regardless of the string contents.

I was curious why they have both string.Compare() and string.CompareOrdinal(). Now, I know the reason. I love to understand the arguments behind string.Compare() behavior. The link you gave is broken. Can you look into that?

Ben.
   
Comments
DavidKiryazi 8-Oct-10 23:51pm
   
No probs. I assumed coz u gave examples of numbers you were only interested in numbers, bad for me to make assumptions in sftawre dev :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900