0

I faced with a problem that string comparison in C# works a bit strange:

"0".CompareTo("@") // is 1 

And I'm very surprised with that because ASCII codes is next:

ASCII '@' // 64
ASCII '0' // 48

If I'm comparing chats or use String.CompareOrdinal everything fine:

'0'>'@' // false
String.CompareOrdinal("0","@") // -16

And in JS it works also as expected:

"0" > "@" // false - in Javascript

Next thing that C# code I can't change - it uses CompareTo.

But I need same sorting rules in Javascript. I can't find any solution smarter than replace '@' sign with the '#' because it ASCII code less than zero:

ASCII '#' // 35

Maybe somebody can explain why:

"0".CompareTo("@") // is 1 

Or suggest better workaround how making comparison the same in Javascript

Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
Artem
  • 691
  • 5
  • 20
  • 1
    `CompareTo` is pretty different to `CompareOrdinal`, you may want to check this: http://stackoverflow.com/questions/6120154/what-is-difference-between-different-string-compare-methods (just a side note for reference) – briosheje Apr 28 '17 at 16:18
  • 2
    The equivalent to `CompareTo` in C# is [`localeCompare` in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare): `"0".localeCompare("@")` also returns `1`. I believe any language will compare letters by the values of their character codes, so it will be the same. In other words: There is no difference. – Felix Kling Apr 28 '17 at 16:21
  • Can't you use equals? – Marco Salerno Apr 28 '17 at 16:28
  • Seems the right way is to use [localCompare](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare). But important that in this case, I should use the same locale as the server. – Artem Apr 28 '17 at 17:15

2 Answers2

2

It's not strange, it's culture specific. I'm not an expert in js but I guess that localeCompare may help you.

-1

CompareTo() will return 1 if the first value is meant to be sorted after the second value (in ascending order), according to its call to String.Compare(firstValue,(String)secondValue, StringComparison.CurrentCulture), which would consider 0 to come after @ in a sorted list for display, so you would have @foo, 0foo, 1foo, afoo, Afoo, foo.

In JavaScript, you can pass a function to Array.sort() that would mimic the behavior for the relevant C# culture.

Mark Cidade
  • 98,437
  • 31
  • 224
  • 236