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

后端 未结 5 933
孤独总比滥情好
孤独总比滥情好 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:12

    First, you should decide whether you compare strings in culture dependent or independent way (e.g. in Russian Culture letters "E" and "Ё" often treats as being the same; Finnish tends to treat "V" and "W" as being the same etc.). Next you should choose whether use or not use case ("a" v. "A"). So there're 6 possible comparisons:

    Ordinal (culture independent) comparisons:

    // Ignore case comparison
    Boolean equals = String.Equals(x, y, StringComparison.OrdinalIgnoreCase);
    // Case comparison
    Boolean equals = String.Equals(x, y, StringComparison.Ordinal);
    

    Current culture comparisons:

    // Current culture, ignore case comparison
    Boolean equals = String.Equals(x, y, StringComparison.CurrentCulture);
    // Current culture, case comparison
    Boolean equals = String.Equals(x, y, StringComparison.CurrentCultureIgnoreCase);
    

    Explicit culture comparisons:

    CultureInfo culture = new CultureInfo("Ru-ru"); // <- Or whatever you want
    
    // Explicit culture, ignore case comparison
    Boolean equals = culture.CompareInfo.Compare(x, y, CompareOptions.IgnoreCase);
    // Explicit culture, case comparison
    Boolean equals = culture.CompareInfo.Compare(x, y, CompareOptions.None);
    

提交回复
热议问题