gpt4 book ai didi

c# - 获取2个字符串之间的差异

转载 作者:行者123 更新时间:2023-11-30 22:01:59 24 4
gpt4 key购买 nike

我正在尝试计算两个字符串之间的差异

例如

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

}
}

custom comparer :

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com