假设我有 2 个字符串。第一个字符串是 x = "abc"
,第二个是 y = "ABC"
。在 C# 中,当我编写以下代码时:
if (x == y)
或
if (x.Equals(y))
返回值为true
。如何检查他们的大小写?
最佳答案
返回值不是true
而是false
,因为 .NET 默认区分大小写。
来自 String.Equals
:
This method performs an ordinal (case-sensitive and culture-insensitive) comparison.
对于 ==
也是如此,因为 String.Equality
operator调用 Equals
:
This operator is implemented using the Equals method, which means the comparands are tested for a combination of reference and value equality. This operator performs an ordinal comparison.
这将不区分大小写地进行比较:
bool equals = x.Equals(y , StringComparison.OrdinalIgnoreCase);
如果你只想知道一个字符是大写还是小写你可以使用这些方法:
bool isUpperChar = Char.IsUpper("ABC"[0]); // yes
bool isLowerChar = Char.IsLower("ABC"[0]); // no
关于c# - 如何比较两个字符串及其大小写符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18378448/