C# 如何比较两个字符串并找到相似度百分比

C# 如何比较两个字符串并找到相似度百分比,c#,string,comparison,C#,String,Comparison,下面的代码完成了这项工作,但需要很多时间。我正在比较两个HTML文件的内容,我已经在MongoDB中保存为字符串。字符串的长度约为30K+,并且有大约250K+的记录可供比较。因此,这项工作花费了相当多的时间 有没有更简单的方法或插件可以使用,而且速度也很快 private int ComputeCost(string input1, string input2) { if (string.IsNullOrEmpty(input1)) return string.IsNu

下面的代码完成了这项工作,但需要很多时间。我正在比较两个HTML文件的内容,我已经在MongoDB中保存为字符串。字符串的长度约为30K+,并且有大约250K+的记录可供比较。因此,这项工作花费了相当多的时间

有没有更简单的方法或插件可以使用,而且速度也很快

private int ComputeCost(string input1, string input2)
{
    if (string.IsNullOrEmpty(input1))
        return string.IsNullOrEmpty(input2) ? 0 : input2.Length;

    if (string.IsNullOrEmpty(input2))
        return string.IsNullOrEmpty(input1) ? 0 : input1.Length;

    int input1Length = input1.Length;
    int input2Length = input2.Length;

    int[,] distance = new int[input1Length + 1, input2Length + 1];

    for (int i = 0; i <= input1Length; distance[i, 0] = i++) ;
    for (int j = 0; j <= input2Length; distance[0, j] = j++) ;

    for (int i = 1; i <= input1Length; i++)
    {
        for (int j = 1; j <= input2Length; j++)
        {
            int cost = (input2[j - 1] == input1[i - 1]) ? 0 : 1;

            distance[i, j] = Math.Min(
                                Math.Min(distance[i - 1, j] + 1, distance[i, j - 1] + 1),
                                distance[i - 1, j - 1] + cost);
        }
    }

    return distance[input1Length, input2Length];
}
private int ComputeCost(字符串input1,字符串input2)
{
if(string.IsNullOrEmpty(input1))
返回字符串.IsNullOrEmpty(input2)?0:input2.Length;
if(string.IsNullOrEmpty(input2))
返回字符串.IsNullOrEmpty(input1)?0:input1.Length;
int input1长度=input1.长度;
int input2Length=input2.长度;
int[,]距离=新int[Input1长度+1,Input2长度+1];

对于(int i=0;i,根据@Kay Lee,将函数设置为静态,并使用HTML agility pack删除不必要的数据。并且看到了良好的性能改进。

这不是“”的作用吗?您正在计算编辑距离,对吗?为什么不比较数据库本身中的字符串?我会尝试一下,因为它通常更快。是的,请尝试,返回(1.0-(ComputeCost(string1,string2)/(double)Math.Max(input1.Length,input2.Length))*100;这给出了相似性百分比。在我的例子中,最关键的一点是通过排除不必要的数据以及使用多线程进行分割和处理来减少数据量。