This article mainly for you in detail the C # calculation of 2 string similarity of the relevant code, with a certain reference value, interested in small partners can refer to
Calculate string similarity, direct to C # code
public static float Levenshtein (string str1, String str2) {//calculates the length of a two string. int len1 = str1. Length; int len2 = str2. Length; Establish the above-mentioned array, a space greater than the length of the character int[,] dif = new Int[len1 + 1, len2 + 1]; Assign the initial value, step b. for (int a = 0; a <= len1; a++) {dif[a, 0] = A; } for (int a = 0; a <= len2; a++) {dif[0, a] = A; }//Calculates whether two characters are the same, computes the value on the left 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; }//Take the smallest dif[i of three values, j] = Math.min (Math.min (dif[i-1, j-1] + temp, dif[i, j-1] + 1), Dif[i-1, J] + 1); }} Console.WriteLine ("String \" "+ str1 +" \ "with \" "+ str2 +" \ "); Take the value in the lower right corner of the array, and the same position represents the comparison of different strings Console.WriteLine ("Difference step:" + Dif[len1, Len2]); Calculates the similarity of float similarity = 1-(float) dif[len1, Len2]/Math.max (str1. Length, str2. Length); Console.WriteLine ("Similarity:" + similarity); return similarity; }
The result is the similarity, the verification code is used to identify the