How to compare two strings and their upper and lower case signs

后端 未结 5 914
孤独总比滥情好
孤独总比滥情好 2021-02-18 23:47

Let\'s say I have 2 strings.First string is x = \"abc\" and the second one is y = \"ABC\".When I write in c# following code:

if(x == y)

or

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-19 00:14

    The return value is not true but false since .NET is case sensitive by default.

    From String.Equals:

    This method performs an ordinal (case-sensitive and culture-insensitive) comparison.

    For == the same is true since String.Equality operator calls 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.

    This will compare case insensitively:

    bool equals = x.Equals(y , StringComparison.OrdinalIgnoreCase);
    

    If you just want to know if a character is upper or lower case you can use these methods:

    bool isUpperChar = Char.IsUpper("ABC"[0]); // yes
    bool isLowerChar = Char.IsLower("ABC"[0]); // no
    

提交回复
热议问题