C# 比较2个字符数组的差异%
我有两个文本框(winforms应用程序)在一个按钮上按下,我有以下代码:C# 比较2个字符数组的差异%,c#,.net,C#,.net,我有两个文本框(winforms应用程序)在一个按钮上按下,我有以下代码: string new_text = txtnew.Text; string old_text = txtold.Text; char[] arr_new = new_text.ToCharArray(); char[] arr_old = old_text.ToCharArray(); double found = 0.0;
string new_text = txtnew.Text;
string old_text = txtold.Text;
char[] arr_new = new_text.ToCharArray();
char[] arr_old = old_text.ToCharArray();
double found = 0.0;
double not_found = 0.0;
foreach (char c_old in arr_old)
{
foreach (char c_new in arr_new)
{
if (c_new == c_old)
{
found++;
}else{
not_found++;
}
}
}
double percentage //need help here..
MessageBox.Show(percentage.ToString());
我一直试图做的是比较每个数组,看看另一个数组中是否存在来自1个数组的字符,然后它应该以百分比的形式输出差异。因此,如果txtNew=“hello worl”和txtold=“hello world”,那么两者的差异将是0.1%?无论如何,修改的次数越多,差异就越大,直到达到60%差异的安全状态。您可以通过将未找到的
除以总数来计算百分比,如下所示:
double percentage = (100.0 * not_found) / (found + not_found);
更精确的方法是计算字符串之间的距离,然后用原始字符串长度的百分比表示该距离(即使用编辑距离,而不是not_found
).如果在内部循环中增加not\u found
,它将增加到old\u text.Length*new\u text.Length
。这将产生巨大的not_found
数字,给你的百分比比我想象的要小得多
此外,执行char数组也没有意义,内部可以由IndexOf
调用替换:
string new_text = txtnew.Text;
string old_text = txtold.Text;
var found = 0;
foreach (var c_old in old_text)
{
if (new_text.IndexOf(c_old) != -1)
{
found++;
}
}
//percentage of characters in the old text that also appear in the new text
double percentage = (100d * found) / old_text.Length;
MessageBox.Show(percentage.ToString());
看看这个维基百科页面:
该页面上提供了一个C#函数,我认为它正是您想要的
编辑:刚刚意识到其他人已经引用了相同的算法,很抱歉重复。+1 Levenshtein FTW。下面是一个C#实现:您是如何得到的。示例中有1%的差异。这更像是10%的差异。这仅在字符串长度完全相同时有效,否则无效。如果9/10个字符匹配,则为90%。为什么不将与字符串长度匹配的字符数除以呢。你可以通过从1减去匹配百分比(差值)来找到区别。你不清楚你认为的区别是狗和上帝0的区别吗?它们的字符都是一样的。@evanmcdonnal-根据他的例子,应该是2/3的字符匹配,所以33%的差异和77%的匹配。@Ramhound听起来是对的:p