简体   繁体   English

比较两个字符串并获得差异

[英]Compare two strings and get the difference

How can i compare two strings in c# and gets the difference? 我如何比较c#中的两个字符串并获得差异?

for example: 例如:

String1 : i have a car String1:我有车

string2 : i have a new car bmw string2:我有一辆新车宝马

result: new, bmw 结果:新的,宝马

You need to make sure the larger set is on the left hand side of the Except (not sure if there is a pure Linq way to achieve that): 您需要确保较大的集合位于Except的左侧(不确定是否有纯Linq方式来实现):

    static void Main(string[] args)
    {
        string s1 = "i have a car a car";
        string s2 = "i have a new car bmw";

        List<string> diff;
        IEnumerable<string> set1 = s1.Split(' ').Distinct();
        IEnumerable<string> set2 = s2.Split(' ').Distinct();

        if (set2.Count() > set1.Count())
        {
            diff = set2.Except(set1).ToList();
        }
        else
        {
            diff = set1.Except(set2).ToList();
        }
    }

Based off your question (It is a bit vague.) this should work. 根据你的问题(这有点模糊。)这应该工作。

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

At the top of your file make sure you include: 在文件的顶部,请确保包括:

using System.Linq;

You can use a difference algorithm for this task. 您可以使用差异算法执行此任务。 The paper " An O(ND) Difference Algorithm and Its Variations " describes a quite powerful algorithm to accomplish this task. 论文“ An O(ND)差分算法及其变化 ”描述了一种非常强大的算法来完成这项任务。 For an implementation in C#, you can have a look at " An O(ND) Difference Algorithm for C# ", but IMHO it surely is more interesting to have a look at the paper and implement it for yourself in case you're interested on how the algorithm works in detail. 对于C#中的实现,你可以看一下“ 用于C#的O(ND)差分算法 ”,但是恕我直言,看看论文并为自己实现它肯定会更有趣,以防你感兴趣该算法如何工作详细。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM