[英]C# String: why string a == b operator gives different answer than a.CompareTo(b) == 0?
I messed with C# a little and found a code that gives very uncomfortable results: 我用C#搞砸了一下,发现了一个非常不舒服的代码:
static void Main(string[] args)
{
string a = "string", b = "string\0";
bool b1 = a == b;
bool b2 = (a.CompareTo(b) > 0);
bool b3 = (a.CompareTo(b) < 0);
bool b4 = (a.CompareTo(b) == 0);
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine("{0} {1} {2} {3}", b1, b2, b3, b4);
}
Output: 输出:
string
string
False False False True
Expected output (on of the): 预期产出(上):
string
string
True False False True
The result of CompareTo
doesn't imply equality, it relates to sort order. CompareTo
的结果并不意味着相等,它与排序顺序有关。 I'm not sure it's too surprising that the null character is ignored for sorting purposes. 我不确定为了排序目的而忽略null字符太令人惊讶了。
Per the documentation : 根据文件 :
Character sets include ignorable characters.
字符集包括可忽略的字符。 The CompareTo(String) method does not consider such characters when it performs a culture-sensitive comparison.
CompareTo(String)方法在执行区域性敏感比较时不考虑此类字符。
You want StringComparison.Ordinal
flag: just compare strings lexicographically: 你想要
StringComparison.Ordinal
标志:只是按字典顺序比较字符串:
...
bool b2 = (a.CompareTo(b, StringComparison.Ordinal) > 0);
bool b3 = (a.CompareTo(b, StringComparison.Ordinal) < 0);
bool b4 = (a.CompareTo(b, StringComparison.Ordinal) == 0);
...
String.CompareTo returns 0 if the string instance has the same position in the sort order as the supplied value. 如果字符串实例在排序顺序中与提供的值具有相同的位置,则String.CompareTo返回0。 This is something different than comparing for equality.
这与比较平等有所不同。 So I would expect the outcome as you describe.
所以我期待你描述的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.