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 -
.
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
?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With