我正在尝试计算两个字符串之间的差异
例如
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);
}
}
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/