Compare two strings and get the difference

前端 未结 3 1900
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 17:55

How can i compare two strings in c# and gets the difference?

for example:

String1 : i have a car

string2 : i have a new car bmw

result: new

3条回答
  •  春和景丽
    2020-12-01 18:29

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

        static void Main(string[] args)
        {
            string s1 = "i have a car a car";
            string s2 = "i have a new car bmw";
    
            List diff;
            IEnumerable set1 = s1.Split(' ').Distinct();
            IEnumerable set2 = s2.Split(' ').Distinct();
    
            if (set2.Count() > set1.Count())
            {
                diff = set2.Except(set1).ToList();
            }
            else
            {
                diff = set1.Except(set2).ToList();
            }
        }
    

提交回复
热议问题