我需要将一些字符串比较从 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/