SoFunction
Updated on 2025-03-07

C# calculates the similarity of 2 strings

Calculate string similarity and directly use C# code

 public static float levenshtein(string str1, string str2)
  {
   //Calculate the length of two strings.   int len1 = ;
   int len2 = ;
   //Create the array mentioned above, which is one space larger than the character length   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 the two characters are the same, calculate the value on the upper 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;
     }
     //Please the smallest of the three values     dif[i, j] = ((dif[i - 1, j - 1] + temp, dif[i, j - 1] + 1), dif[i - 1, j] + 1);
    }
   }
   ("String\"" + str1 + "\"and\"" + str2 + "\"Comparison");

   //Take the value in the lower right corner of the array, and the same position represents the comparison of different strings.   ("Difference Steps:" + dif[len1, len2]);
   //Calculate similarity   float similarity = 1 - (float)dif[len1, len2] / (, );
   ("Similarity:" + similarity);
   return similarity;
  }

The result is similarity, and the verification code is used to identify the

Love to template website provides

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.