c# - 如何比较两个字符串及其大小写符号

标签 c# string visual-studio-2010

假设我有 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/

相关文章:

c# - Linq 中的排序和唯一记录

扩展 DataMediaSource 时出现 Java.Lang.NoClassDefFoundError

string - bash:将字符串变量解释为文件名/路径

wpf - 为什么是 Visual Studio x86 中 WPF 应用程序的默认平台目标,而不是 AnyCPU?

visual-studio-2010 - 如何使用 VS2010 中的 MSBuild 在解决方案中定位特定的 .NET 项目?

c# - 无法通过嵌套类型访问外部类型的非静态成员

java - 在循环内命名字符串

c++ - 返回 char1 + char2?不可能吗?

visual-studio-2010 - TFS 2010版本控制

c# - WPF Canvas 中的网格线