C# string comparison ignoring spaces, carriage return or line breaks

前端 未结 10 958
执念已碎
执念已碎 2020-12-05 13:07

How can I compare 2 strings in C# ignoring the case, spaces and any line-breaks. I also need to check if both strings are null then they are marked as same.

Thanks!<

10条回答
  •  生来不讨喜
    2020-12-05 13:29

    You should normalize each string by removing the characters that you don't want to compare and then you can perform a String.Equals with a StringComparison that ignores case.

    Something like this:

    string s1 = "HeLLo    wOrld!";
    string s2 = "Hello\n    WORLd!";
    
    string normalized1 = Regex.Replace(s1, @"\s", "");
    string normalized2 = Regex.Replace(s2, @"\s", "");
    
    bool stringEquals = String.Equals(
        normalized1, 
        normalized2, 
        StringComparison.OrdinalIgnoreCase);
    
    Console.WriteLine(stringEquals);
    

    Here Regex.Replace is used first to remove all whitespace characters. The special case of both strings being null is not treated here but you can easily handle that case before performing the string normalization.

提交回复
热议问题