
c#计算2个字符串的相似度
发布日期:2021-05-09 00:53:46
浏览次数:15
分类:博客文章
本文共 1757 字,大约阅读时间需要 5 分钟。
���������������
public static float levenshtein(string str1, string str2) { //��������������������������������� int len1 = str1.Length; int len2 = str2.Length; //��������������������������������������������������������� int[,] dif = new int[len1 + 1, len2 + 1]; //������������������B��� for (int a = 0; a <= len1; a++) { dif[a, 0] = a; } for (int a = 0; a <= len2; a++) { dif[0, a] = a; } //��������������������������������������������������� int temp; for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { if (str1[i - 1] == str2[j - 1]) { temp = 0; } else { temp = 1; } //������������������������ dif[i, j] = Math.Min(Math.Min(dif[i - 1, j - 1] + temp, dif[i, j - 1] + 1), dif[i - 1, j] + 1); } } Console.WriteLine("���������\"" + str1 + "\"���\"" + str2 + "\"���������"); //��������������������������������������������������������������������������� Console.WriteLine("���������������" + dif[len1, len2]); //��������������� float similarity = 1 - (float)dif[len1, len2] / Math.Max(str1.Length, str2.Length); Console.WriteLine("������������" + similarity); return similarity; }
������������������������������������������������������������
��������������� http://2gei.cn ������