c# - 了解字符串比较行为

标签 c#

我需要将一些字符串比较从 vb 转换为 c#。 vb 代码使用 > 和 < 运算符。我希望用标准框架字符串比较方法替换它。但是,有一种行为我不明白。为了复制这个,我有这个测试

[TestMethod]
public void TestMethod2()
{
    string originalCulture = CultureInfo.CurrentCulture.Name; // en-GB

    var a = "d".CompareTo("t");  // returns -1
    var b = "T".CompareTo("t");  // returns 1

    Assert.IsTrue(a < 0, "Case 1");
    Assert.IsTrue(b <= 0, "Case 2");
}

有人可以解释为什么 b 返回 1。我目前的理解是,如果它区分大小写,那么“T”应该在排序顺序中位于“t”之前,即 -1。如果它不区分大小写,它将是相同的,即 0

(仅供引用 .Net Framework 4.5.2)

非常感谢

最佳答案

小写字母在大写字母之前。 对于 en-GB 和 InvariantCulture 都是如此。

如果你想要类似 ASCII 的行为,你应该指定额外的 CompareOptions.Ordinal 参数

请参阅以下内容:

关于 repl.it 的示例代码:

using System;
using System.Globalization;
using System.Collections.Generic;

class MainClass
{
    public static void Main(string[] args)
    {

        //All the following case sensitive comparisons puts d before D
        Console.WriteLine("D".CompareTo("d"));
        Console.WriteLine(String.Compare("D", "d", false));
        Console.WriteLine(String.Compare("D", "d", false, CultureInfo.InvariantCulture));

        //All the following case sensitive comparisons puts capital D before small letter d
        Console.WriteLine(String.Compare("D", "d", CultureInfo.InvariantCulture, CompareOptions.Ordinal));

        //The following is case insensitive
        Console.WriteLine(String.Compare("D", "d", true));

        //The default string ordering in my case is d before D
        var list = new List<string>(new[] { "D", "d" });
        list.Sort();
        foreach (var s in list)
        {
            Console.WriteLine(s);
        }
    }
}

//Results on repl.it
//Mono C# compiler version 4.0.4.0
//   
//1
//1
//1
//-32
//0
//d
//D

祝你好运

埃亚尔

关于c# - 了解字符串比较行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45235074/

相关文章:

c# - 获取在 gridview 中使用的日期选择器的值

c# - 参数超出范围

c# - 在 C# 中嵌入 IronPython 时如何处理值类型?

C# 图像分析库

C#如何将object中的所有空列表变成null

c# - 为什么 "abcd".StartsWith ("") 返回真?

c# - 从相关数据库中获取值(value)

c# - 在 C# 中更改 Excel 电子表格的 PivotCache 连接

c# - 原始列表的浅克隆列表中的项目被清除会发生什么

c# - 删除现有版本并安装 msi 安装程序