Tuesday, May 21, 2013

C#- Find Similarity between Two Strings in Percentage

In this post, I am explaining how can you check the similarity between two strings in terms of percentage in  C# ? To check similarity between two strings we have formula by which we can find similarity in %.

In my previous posts, I explained Create Hindi TextBox Using Google Transliteration in ASP.Net, Convert Multipage Tiff file into PDF in ASP.Net using C#, Send mail in ASP.Net, Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

The formula to check the similarity between two strings in % is-

Similarity (%) = 100 * (CommonItems * 2) / (Length of String1 + Length of String2)

Let's see some example-
C# Code

Similarity in % between Strings
public static void SmilarityinPercentage()
 {
   string string1 = "Manish";
   string string2 = "Mahesh";
   char[] charString1 = string1.ToCharArray();
   char[] charString2 = string2.ToCharArray();
   var strCommon = charString1.Intersect(charString2);
   //Formula : Similarity (%) = 100 * (CommonItems * 2) / (Length of String1 + Length of String2)
   double Similarity = (double)(100 * (strCommon.Count() * 2)) / (charString1.Length + charString2.Length);
   Console.WriteLine("Strings are {0}% similar", Similarity.ToString("0.00"));   
}
//Output:- Strings are 66.67% similar

Similarity in % between Arrays of String
public void SmilarityinPercentage()
{
  string[] string1 = new string[] {"Manish","Dubey", "Dot", "Net","World" };
  string[] string2 = new string[] { "Dot", "Net", "World" };
  var strCommon = string1.Intersect(string2);
  //Formula : Similarity (%) = 100 * (CommonItems * 2) / (Length of String1 + Length of String2)
  double Similarity = (double)(100 * (strCommon.Count() * 2)) / (string1.Length + string2.Length);
  Console.WriteLine("Strings are {0}% similar", Similarity.ToString("0.00"));
}
//Output:- Strings are 75.00% similar

Similarity in % between String Sentences
public void SmilarityinPercentage()
{
  string string1 = "My blog name is Dot Net World";
  string string2 = "Dot Net World";
  string[] splitString1 = string1.Split(' ');
  string[] splitString2 = string2.Split(' ');
  var strCommon = splitString1.Intersect(splitString2);
  //Formula : Similarity (%) = 100 * (CommonItems * 2) / (Length of String1 + Length of String2)
  double Similarity = (double)(100 * (strCommon.Count() * 2)) / (splitString1.Length + splitString2.Length);
   Console.WriteLine("Strings are {0}% similar", Similarity.ToString("0.00"));  
}
//Output:- Strings are 60.00% similar

I hope you enjoyed this post. I would like to have any feedback from you. Your valuable feedback, question, or comments about this article are always welcome.

No comments:

Post a Comment

^ Scroll to Top