Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does CompareTo not sort my string using ASCII code ordering?

Tags:

string

c#

In C# "123-delete.json".CompareTo("123.json") evaluates to 1, meaning "123-delete.json" is to be sorted after "123.json".

This is unexpected for me, as according to the ASCII table . comes after -.

enter image description here

I tried to browse the CompareTo implementation on GitHub, but it seems this logic is implemented in a native function (InternalCompareString).

Why does the CompareTo method not follow the ASCII ordering?

Also, is there a way to view the source code for native functions such as InternalCompareString?

like image 930
Dušan Rychnovský Avatar asked Aug 20 '19 09:08

Dušan Rychnovský


People also ask

How do you sort a string in ascii order?

Make the string S as an empty string. Iterate over the range [0, N) using the variable i and iterate over the range [0, freq[i]) using the variable j and adding the character corresponding to the i-th ASCII value in the string s[]. After performing the above steps, print the string S as the result.


1 Answers

Use

string.Compare("123-delete.json", "123.json", StringComparison.Ordinal)

or

string.CompareOrdinal("123-delete.json", "123.json")

or

StringComparer.Ordinal.Compare("123-delete.json", "123.json")

In C# the comparison of strings is by default culture dependent and StringComparison.Ordinal lets the function compre the strings based on binary sort rules.

As @JeppeStigNielsen mentioned, the object returned by StringComparer.Ordinal implements the IComparer<string> interface, this lets you use this kind of sorting order in scenarios where you have a SortedSet<string>, SortedList<string> or any kind of "set" of strings that make use of an compare-object.

like image 129
Ackdari Avatar answered Oct 23 '22 17:10

Ackdari