artwl
artwl

Reputation: 3582

about string.compare method

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?

Upvotes: 3

Views: 410

Answers (3)

KeithS
KeithS

Reputation: 71563

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.

Upvotes: 4

user596075
user596075

Reputation:

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
)

Upvotes: 3

Jared Shaver
Jared Shaver

Reputation: 1339

The - is treated as a special case in sorting by the .NET Framework. This answer has the details: https://stackoverflow.com/a/9355086/1180433

Upvotes: 1

Related Questions