Home > Backend Development > C#.Net Tutorial > Sample code sharing on how to calculate the similarity between two strings in C#

Sample code sharing on how to calculate the similarity between two strings in C#

黄舟
Release: 2017-06-04 09:33:02
Original
1566 people have browsed it

This article mainly introduces the code related to calculating the similarity of two strings in detail. It has certain reference value. Interested friends can refer to it. Calculate the string similarity, come directly to the C# code

 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;
  }
Copy after login

The returned result is the similarity,

Verification code

It is used for identification

The above is the detailed content of Sample code sharing on how to calculate the similarity between two strings in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template