Calculate similarity between two strings in C#
This article illustrates the different techniques to calculate the similarity between two strings in C#.
We can use the Edit distance algorithm to determine the similarity between two strings in C#. The Edit distance algorithm tells us how different two strings are from each other by finding the least number of moves (add, remove, insert) required to convert one string to another. We can even use the Jaro-Winkler distance algorithm instead of Edit distance.
The following code provides the C# implementation of the Edit distance algorithm and uses it to find the similarity between two given strings:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
using System; public class Example { public static int getEditDistance(string X, string Y) { int m = X.Length; int n = Y.Length; int[][] T = new int[m + 1][]; for (int i = 0; i < m + 1; ++i) { T[i] = new int[n + 1]; } for (int i = 1; i <= m; i++) { T[i][0] = i; } for (int j = 1; j <= n; j++) { T[0][j] = j; } int cost; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { cost = X[i - 1] == Y[j - 1] ? 0: 1; T[i][j] = Math.Min(Math.Min(T[i - 1][j] + 1, T[i][j - 1] + 1), T[i - 1][j - 1] + cost); } } return T[m][n]; } public static double findSimilarity(string x, string y) { if (x == null || y == null) { throw new ArgumentException("Strings must not be null"); } double maxLength = Math.Max(x.Length, y.Length); if (maxLength > 0) { // optionally ignore case if needed return (maxLength - getEditDistance(x, y)) / maxLength; } return 1.0; } public static void Main() { string s1 = "Techie Delight"; string s2 = "Tech Delight"; double similarity = findSimilarity(s1, s2); Console.WriteLine(similarity); // 0.8571428571428571 } } |
The above code calculates the similarity between two strings in the closed range [0, 1]. We can easily modify the return value of the findSimilarity() routine to calculate similarity in percentage (return value x 100).
That’s all about calculating the similarity between two strings in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)