我想与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");
}
你能帮我比较一下吗?
答案 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))