比较两个字符串并得到差异 [英] Compare two strings and get the difference
本文介绍了比较两个字符串并得到差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何比较c#中的两个字符串并获得差值?
How can i compare two strings in c# and gets the difference?
例如:
String1 :我有车
String1 : i have a car
字符串2:我有新车宝马
string2 : i have a new car bmw
结果:新车,宝马
推荐答案
您需要确保较大的集合位于例外$ c的左侧$ c>(不确定是否可以通过纯Linq方式实现):
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<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();
}
}
这篇关于比较两个字符串并得到差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文