长度为 1 的字符串比较给出的结果与字符比较不同……为什么?

1-length string comparison gives different result than character comparison... why?

我是 C# 的新手,我在字符串比较中发现了一些我不太理解的意想不到的东西。

有人可以解释一下为什么字符之间的比较给出与以下代码中一个字符长度字符串的比较相反的结果吗?

我预计 "9" < "=" 将是 true(因为 unicode 代码 '9' (57) 小于 unicode 代码 '=' (61) )但它是错误的.. . 后面字符串的比较逻辑是什么,为什么和字符比较不一样?

代码:

bool resChComp = '9' < '=';
bool resStrComp = String.Compare("9", "=") < 0;

Console.WriteLine($"\n'9' < '=' : {resChComp}, \"9\" < \"=\" : { resStrComp }");

输出:

'9' < '=' : True, "9" < "=" : False

在字符比较的情况下,字符将被转换为对应于ASCII值的int9 的 ASCII 值为 57,而 = 的值为 61。这意味着字符串比较和字符比较不是在比较完全相同的东西(这就是为什么它们可能有不同的结果) .

这是因为 String.Compare 默认使用单词排序顺序,而不是字符的数值。恰好对于所使用的区域性,9 在排序顺序中排在 = 之前。

如果您指定序数(二进制)排序规则,如前所述here,它将按您预期的方式工作。

bool resStrComp = String.Compare("9", "=", StringComparison.Ordinal) < 0;

默认的字符串比较是 'word sort'。 From the documentation,

The .NET Framework uses three distinct ways of sorting: word sort, string sort, and ordinal sort. Word sort performs a culture-sensitive comparison of strings. Certain nonalphanumeric characters might have special weights assigned to them. For example, the hyphen ("-") might have a very small weight assigned to it so that "coop" and "co-op" appear next to each other in a sorted list. String sort is similar to word sort, except that there are no special cases. Therefore, all nonalphanumeric symbols come before all alphanumeric characters. Ordinal sort compares strings based on the Unicode values of each element of the string.

您期望的比较是序号比较,您可以通过在 String.Compare 重载中使用 StringComparison.Ordinal 来获得,如下所示:

bool resStrComp = String.Compare("9", "=", StringComparison.Ordinal) < 0;

这将通过使用它们的 unicode 值来比较字符串,就像将一个字符与另一个字符进行比较一样。