为什么字符串“\ u0022”以此字符串“\ u204D”开头

时间:2015-01-15 22:54:00

标签: c# .net unicode string-comparison

为什么在.net(Windows 8)下这个字符串比较会返回true?

"\u0022".StartsWith("\u204D");

在所有文化中都是如此,如果将StartsWith切换为Equals,则返回false。

对于StartsWith比较,有许多不同的字符返回true。这是奇怪的Unicode规则的一部分还是Windows在这里有自己的规则?

1 个答案:

答案 0 :(得分:0)

要知道依赖于文化的字符串比较有哪些规则并不容易。标点符号U + 0022 "(引号)和U + 204D (BLACK RIGHTWARDS BULLET)被认为是#34;足够相等"在文化比较下(包括不变文化的比较)。这些例子都表明:

// culture-sensitive:

Console.WriteLine("\"".StartsWith("⁍"));
Console.WriteLine("⁍".StartsWith("\""));
Console.WriteLine("\"".StartsWith("⁍", StringComparison.InvariantCulture));
Console.WriteLine("⁍".StartsWith("\"", StringComparison.InvariantCulture));

Console.WriteLine("\"".Equals("⁍", StringComparison.CurrentCulture));
Console.WriteLine("⁍".Equals("\"", StringComparison.CurrentCulture));
Console.WriteLine("\"".Equals("⁍", StringComparison.InvariantCulture));
Console.WriteLine("⁍".Equals("\"", StringComparison.InvariantCulture));

Console.WriteLine(StringComparer.CurrentCulture.Equals("\"", "⁍"));
Console.WriteLine(StringComparer.CurrentCulture.Equals("⁍", "\""));
Console.WriteLine(StringComparer.InvariantCulture.Equals("\"", "⁍"));
Console.WriteLine(StringComparer.InvariantCulture.Equals("⁍", "\""));

Console.WriteLine("\"".CompareTo("⁍"));
Console.WriteLine("⁍".CompareTo("\""));

Console.WriteLine(StringComparer.CurrentCulture.Compare("\"", "⁍"));
Console.WriteLine(StringComparer.CurrentCulture.Compare("⁍", "\""));
Console.WriteLine(StringComparer.InvariantCulture.Compare("\"", "⁍"));
Console.WriteLine(StringComparer.InvariantCulture.Compare("⁍", "\""));

可以提供其他示例,例如static上的string方法,但它们是等效的。

通过序数比较,当然U + 0022必须与(小于)U + 204D不同(这很简单!):

// ordinal:

Console.WriteLine("\"".StartsWith("⁍", StringComparison.Ordinal));
Console.WriteLine("⁍".StartsWith("\"", StringComparison.Ordinal));

Console.WriteLine("\"".Equals("⁍"));
Console.WriteLine("⁍".Equals("\""));

Console.WriteLine(StringComparer.Ordinal.Equals("\"", "⁍"));
Console.WriteLine(StringComparer.Ordinal.Equals("⁍", "\""));

Console.WriteLine(StringComparer.Ordinal.Compare("\"", "⁍"));
Console.WriteLine(StringComparer.Ordinal.Compare("⁍", "\""));