比较具有不同转义字符的不同操作系统的C#中的字符串

时间:2018-04-18 07:23:05

标签: c# string compare

我想与C#中的字符串进行比较。到现在为止还挺好。挑战在于这些字符串具有不同的转义字符,因为它们来自不同的系统。字符串“b”显示在Windows窗体元素中,而字符串“a”从Web应用程序中读取。 “等于” - 方法告诉字符串是不同的。 但由于字符串相同但新行,我想知道是否有可能比较这些字符串,无论新行如何编码。

string a = "My cool string\r\nwith two lines";
string b = "My cool string\nwith two lines";

if (a.Equals(b)){
    Debug.WriteLine("Strings match");
}else{
    Debug.WriteLine("Strings do not match");
}

你能帮我比较一下吗?

1 个答案:

答案 0 :(得分:2)

你不能开箱即用,但这种扩展方法可以:

public static class ExtensionMethods
{
    public static bool EqualsIgnoringLinefeed(this string s1, string s2)
    {
        if (s1 == null && s2 == null)
        {
            return true;
        }

        if (s1 == null || s2 == null)
        {
            return false;
        }

        if (s1.Equals(s2))
        {
            return true;
        }

        s1 = s1.Replace("\r\n", "\n").Replace("\r", "\n");
        s2 = s2.Replace("\r\n", "\n").Replace("\r", "\n");

        return s1.Equals(s2);
    }
}

这样称呼:

if (a.EqualsIgnoringLinefeed(b))