Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ASCII comparison and string comparison

I am using C#. When I am comparing two char value its sending me correct output, like,

'-'.CompareTo('!') //Its sending me positive value 12

means '-' > '!' is true

But when I am comparing two string of same value its sending me different result

"-".CompareTo("!") //Its sending me negative value -1

means "-" > "!" is false

Can anyone please explain me why it is doing so ? Should not it be 'true' for both cases ?

like image 496
Arnab Avatar asked Jul 25 '14 07:07

Arnab


People also ask

What is the difference between ASCII and Unicode?

Unicode is the universal character encoding used to process, store and facilitate the interchange of text data in any language while ASCII is used for the representation of text such as symbols, letters, digits, etc. in computers. It is a character encoding standard for electronic communication.

How do I compare string references?

When two separate string instances contain the exact same sequence of characters, the values of the strings are equal, but the references are different. As described in Section 7.9.6, the reference type equality operators can be used to compare string references instead of string values. Not the answer you're looking for?

How do string equality operators compare string values?

The string equality operators compare string values rather than string references. When two separate string instances contain the exact same sequence of characters, the values of the strings are equal, but the references are different.

What is the use of compare string in Java?

string.Compare Compares two specified String objects and returns an integer that indicates their relative position in the sort order.


1 Answers

String's Compare method is culture specific. That's why you get different results. use string.CompareOrdinal instead, which is byte by byte comparison.

var v = '-'.CompareTo('!');//12
var s = string.CompareOrdinal("-", "!");//12

Best Practices for Using Strings in the .NET Framework

like image 83
Sriram Sakthivel Avatar answered Oct 04 '22 03:10

Sriram Sakthivel