gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:05:16 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com