About the string.compare method

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?

+3


source to share


3 answers


By default, string mapping uses culture-specific settings. These settings allow you to vary the order and weights to apply to letters and symbols; for example, "resume" and "resume" will look pretty close together when sorted using most culture settings, because "é" is ordered immediately after "e" and long before "f", although the Unicode codepage is placed in zero after the rest of the English alphabet. Likewise, characters that are not whitespace occupy a position on the string but are considered "connecting" like dashes, forward slashes, etc., give low "weight" so that they are considered tiebreaks only. This means that "ab" will be sorted right after "ab" and before "ac",because the dash is less important than the letters.



What you see fit is an "ordinal sort", where strings are sorted based on the first difference in the string, based on the relative ordinal positions of the various Unicode characters. This would mean "-d" before "a" if "-" also appears before "a", because the dash is considered a complete "character" and is compared to the character "a" at the same position. However, in the list of real words in this order the words "redo", "resume", "rosin", "ruble", "re-do" and "résumé" will be placed in the order when in the sorted list, which may not make sense in context and certainly not for a non-English speaker.

+4


source


It compares the position of the symbols within each other. In other words, "-" precedes (less than) "a".

String.Compare()

uses word sorting rules when comparing. Note that these are all relative positions. Here is some information from MSDN .

Value : Condition

Negative: strA is less than strB
Zero: strA is equal to strB
Positive: strA is greater than strB



The above comparison applies to this overload:

public static int Compare(
    string strA,
    string strB
)

      

+3


source


The - seen as a special case when sorting .NET Framework. This answer contains the following details: fooobar.com/questions/28897 / ...

+1


source







All Articles