c# - 获取2个字符串之间的差异

标签 c# .net string comparison

我正在尝试计算两个字符串之间的差异

例如

string val1 = "Have a good day";
string val2 = "Have a very good day, Joe";

结果将是一个字符串列表,其中包含 2 个项目“very”和“, Joe”

到目前为止,我对这项任务的研究还没有太多成果

编辑:结果可能需要是 2 个单独的字符串列表,一个包含添加内容,另一个包含删除内容

最佳答案

这是我能想到的最简单的版本:

class Program
{
    static void Main(string[] args)
    {
        string val1 = "Have a good day";
        string val2 = "Have a very good day, Joe";

        MatchCollection words1 = Regex.Matches(val1, @"\b(\w+)\b");
        MatchCollection words2 = Regex.Matches(val2, @"\b(\w+)\b");

        var hs1 = new HashSet<string>(words1.Cast<Match>().Select(m => m.Value));
        var hs2 = new HashSet<string>(words2.Cast<Match>().Select(m => m.Value));

        // Optionaly you can use a custom comparer for the words.
        // var hs2 = new HashSet<string>(words2.Cast<Match>().Select(m => m.Value), new MyComparer());

        // h2 contains after this operation only 'very' and 'Joe'
        hs2.ExceptWith(hs1); 

    }
}

custom comparer :

public class MyComparer : IEqualityComparer<string>
{
    public bool Equals(string one, string two)
    {
        return one.Equals(two, StringComparison.OrdinalIgnoreCase);
    }

    public int GetHashCode(string item)
    {
        return item.GetHashCode();
    }
}

关于c# - 获取2个字符串之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27254729/

相关文章:

c++ - 格式化和查找文本 C++

c++ - 用一些字符串替换字符串中的字符

c# - .NET 中如何实例化类和嵌套类?

c# - C# : strip a path using the characters after each numeric value 中的字符串操作

c# - 使用 C# 使用 OAuth token 的 Twitter 应用程序

c# - 如何在 MathNet 中找到最大矩阵元素?

.net - 为什么编译器认为这是一个 Object 而不是 DataRow?

c# - Excel 打印预览

c# - 遇到锁时如何停止线程?

Swift:检查 UISearchBar.text 是否包含 url