简体   繁体   English

C#String:为什么字符串a == b运算符给出的答案不同于a.CompareTo(b)== 0?

[英]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.

相关问题 为什么a.compareTo(b)等于compareTo(a,b)或a.method(b)= method(a,b)? - Why a.compareTo(b) is equal to compareTo(a,b) or a.method(b) = method(a,b)? 为什么Java中的字符串比较(CompareTo)比C#更快? - Why are String comparisons (CompareTo) faster in Java than in C#? 如何从c#中输入的字符串(a + b)获取运算符类型? - how to get the Operator type from the string(a + b) Input in c#? 在C#中使用过滤字符串A过滤B - Using filter string A to filter for B in C# C#:如何使用正则表达式匹配字符串&#39;@ A = 1,@ B = 2,@ C = 3,...” - C#: How to use regex to match string '@A=1, @B=2, @C=3, …" A运算符&(B l,B r)的C#重载运算符 - C# overloading operators of A operator&(B l,B r) 如何在 C# 中将“=?utf-8?B?...?=”解码为字符串 - How to Decode “=?utf-8?B?…?=” to string in C# 在 C# 中使用元组,(A,B,C)与元组<string, string, string></string,> - Using tuples in C#, (A, B, C) vs Tuple<string, string, string> 将“ [[a],{b},{c}]”拆分为字符串数组“ a,b,c”的最佳方法是什么 - What is the best way to split “[{a},{b},{c}]” into a string array “a,b,c” C#Haversine实现与googlemaps / movable-type.co.uk提供的答案不同 - c# haversine implementation gives different answer than googlemaps/movable-type.co.uk
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM