C Calculates the similarity of two strings
- 2021-12-19 06:35:08
- OfStack
Calculate the string similarity and come directly to C # code
public static float levenshtein(string str1, string str2)
{
// Calculates the length of two strings.
int len1 = str1.Length;
int len2 = str2.Length;
// Create the array mentioned above, which is larger than the character length 1 Individual space
int[,] dif = new int[len1 + 1, len2 + 1];
// Assign 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;
}
// Calculate whether two characters are 1 Sample, calculate the upper left value
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 3 The smallest of the values
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(" String \"" + str1 + "\" And \"" + str2 + "\" Comparison of ");
// Take the value in the lower right corner of the array, and the same different positions represent the comparison of different strings
Console.WriteLine(" Difference steps: " + dif[len1, len2]);
// Calculate similarity
float similarity = 1 - (float)dif[len1, len2] / Math.Max(str1.Length, str2.Length);
Console.WriteLine(" Similarity: " + similarity);
return similarity;
}
The return result is the similarity, which is used in verification code recognition
Love provides template network