C# 字符串 : why string a == b operator gives different answer than a. CompareTo(b) == 0?

标签 c# string comparison

我稍微弄乱了 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);
    }

输出:

string
string
False False False True

预期输出(关于):

string
string
True False False True

最佳答案

CompareTo 的结果并不意味着相等,它与排序顺序有关。我不确定出于排序目的而忽略空字符是否太令人惊讶。

根据 the documentation :

Character sets include ignorable characters. The CompareTo(String) method does not consider such characters when it performs a culture-sensitive comparison.

关于C# 字符串 : why string a == b operator gives different answer than a. CompareTo(b) == 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38728101/

相关文章:

c# - 使用 IHubContext 实例化 SignalR Hub 对象

string - CMake 整数比较不起作用

Javascript 字符串替换 : Can we use a string as the first argument (for speed) but "match globally"?

c# - 在 C# 中有选择地触发事件

c# - 如何将十六进制值解析为一个单位?

c# - float 的乘法性能不一致

python - 类型 <type 'numpy.string_' > 和 <type 'str' > 有什么区别?

c++ - 这是一个好主意吗 : Class that sums pointers from a vector, 这样相等比较很快

c - 日期比较以查找 C 中哪个更大

javascript - === 和 == 如何以不同方式处理 null 比较?