【问题标题】:Compare strings in C# from different OSs with different escape characters比较来自不同操作系统的 C# 中具有不同转义字符的字符串
【发布时间】:2018-04-18 07:23:04
【问题描述】:

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

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");
}

你能帮我比较一下吗?

【问题讨论】:

  • 你可以做的是,先将所有“\n”和“\r\n”替换为空字符串,然后比较字符串
  • 我不知道它会是什么,但我想有一个正则表达式可以比较两个 Strings 而忽略特定的字符序列。
  • 看起来this 可能会覆盖它。
  • 嗯,这可能没有我想象的那么有用
  • 以前unix是\n,mac是\r,windows是\r\n ..

标签: c# string compare


【解决方案1】:

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

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))

【讨论】:

  • 很好,但我会在扩展方法中添加一个StringComparison 参数,以涵盖序数/不变的文化/案例选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-24
  • 2014-03-18
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
  • 2019-04-21
  • 1970-01-01
相关资源
最近更新 更多