using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace System { public static class StringExt { /// <summary> /// 獲取最小數值 /// </summary> private static int getMin(int a, int b, int c) { var min = Math.Min(a, b); return Math.Min(min, c); } /// <summary> /// 字符距離算法,獲取字符編輯距離 /// </summary> public static int Levenshtein_Distance(this string str1, string str2) { int[,] Matrix; int n = str1.Length; int m = str2.Length; char c1, c2; int temp = 0; int i, j = 0; if (n == 0) return m; if (m == 0) return n; Matrix = new int[n + 1, m + 1]; for (i = 0; i <= n; i++) { Matrix[i, 0] = i; } for (j = 0; j <= m; j++) { Matrix[0, j] = j; } for (i = 1; i <= n; i++) { c1 = str1[i - 1]; for (j = 1; j <= m; j++) { c2 = str2[j - 1]; if (c1.Equals(c2)) { temp = 0; } else { temp = 1; } Matrix[i, j] = getMin(Matrix[i - 1, j] + 1, Matrix[i, j - 1] + 1, Matrix[i - 1, j - 1] + temp); } } return Matrix[n, m]; } /// <summary> /// 獲取字符相識度 /// </summary> public static decimal GetSimilarity(this string str1, string str2) { var l = str1.Levenshtein_Distance(str2); return 1 - (decimal)l / Math.Max(str1.Length, str1.Length); } } }
調用方法算法
//獲取字符編輯距離 var l = textBox1.Text.ToString().Levenshtein_Distance(textBox2.Text); //獲取字符相識度 decimal Similarity = textBox1.Text.GetSimilarity(textBox2.Text);