How to display word differences using c#?

自作多情 提交于 2019-12-02 19:13:46
Jim Geurts

Microsoft has released a diff project on CodePlex that allows you to do word, character, and line diffs. It is licensed under Microsoft Public License (Ms-PL).

https://github.com/mmanela/diffplex

Other than a few general optimizations, if you need to include the separators in the comparison you are essentially doing a character by character comparison with breaks. Though you could use the O(ND) you linked, you are going to make as many changes to it as you would basically writing your own.

The main problem with difference comparison is finding the continuation (if I delete a single word, but leave the rest the same).

If you want to use their code start with the example and do not write the deleted characters, if there are replaced characters in the same place, do not output this result. You then need to compute the longest continuous run of "changed" words, highlight this string and output.

Sorry thats not much of an answer, but for this problem the answer is basically writing and tuning the function.

Well String.Split with '\n', ' ' and '\t' as the split characters will return you an array of words in your block of text.

You could then compare each array for differences. A simple 1:1 comparison would tell you if any word had been changed. Comparing:

hello world how are you

and:

hello there how are you

would give you that world and changed to there.

What it wouldn't tell you was if words had been inserted or removed and you would still need to parse the text blocks character by character to see if any of the separator characters had been changed.

string string1 = "hello world how are you"; string string2 = "hello there how are you";

        var first = string1.Split(' ');
        var second = string2.Split(' ');
        var primary = first.Length > second.Length ? first : second;
        var secondary = primary == second ? first : second;
        var difference = primary.Except(secondary).ToArray();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!