Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
While comparing two strings for sorting using string.CompareTo(), unexpected result comes.

Paste below code in the main method.

C#
String str9 = "Output 9";
String str11 = "Output 11";

int nine_11 = str9.CompareTo(str11);


The value returned is one(1) means str9 is greater than str11. However, I was expecting it to be -1.

Any idea to overcome this.
Posted
Comments
Richard MacCutchan 24-Oct-13 5:39am    
The character '9' is greater than the character '1'. See http://alasir.com/books/bsd/appendix-f.html.

1 solution

That is correct, it is called lexicographic comparison. As Richard pointed out, the character '1' is less than character '9'.
What you (possibly) expected was a combined compare, that is lexicographic on the heading strings (that is "Output ") and numeric on the trailing ones ( "9", "11"). That is not automatic you have to write yourself some (simple) code.
 
Share this answer
 

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