Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

about string.compare method

Tags:

c#

compare

a strange question,my code is:

static void Main(string[] args)
{
    Console.WriteLine(string.Compare("-", "a"));//output -1
    Console.WriteLine(string.Compare("-d", "a"));//output 1
    Console.Read();
}

who can tell me why?

like image 346
artwl Avatar asked Sep 02 '26 02:09

artwl


2 Answers

By default, string comparison uses culture-specific settings. These settings allow for varying orders and weights to be applied to letters and symbols; for instance, "resume" and "résumé" will appear fairly close to each other when sorting using most culture settings, because "é" is ordered just after "e" and well before "f", even though the Unicode codepage places é well after the rest of the English alphabet. Similarly, symbols that aren't whitespace, take up a position in the string, but are considered "connective" like dashes, slashes, etc are given low "weight", so that they are only considered as tie-breakers. That means that "a-b" would be sorted just after "ab" and before "ac", because the dash is less important than the letters.

What you think you want is "ordinal sorting", where strings are sorted based on the first difference in the string, based on the relative ordinal positions of the differing characters in the Unicode codepage. This would place "-d" before "a" if "-" would also come before "a", because the dash is considered a full "character" and is compared to the character "a" in the same position. However, in a list of real words, this would place the words "redo", "resume", "rosin", "ruble", "re-do", and "résumé" in that order when in an ordinal-sorted list, which may not make sense in context, and certainly not to a non-English speaker.

like image 198
KeithS Avatar answered Sep 04 '26 15:09

KeithS


It compares the position of the characters within each other. In other words, "-" comes before (is less than) "a".

String.Compare() uses word sort rules when comparing. Mind you, these are all relative positions. Here is some information from MSDN.

Value : Condition

Negative : strA is less than strB
Zero : strA equals strB
Positive : strA is greater than strB

The above comparison applies to this overload:

public static int Compare(
    string strA,
    string strB
)

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!