c# - Visualizing differences in 2+ plain text strings -
i'm looking way show differences between 2 or more texts (side side). don't need able create patch or that--just show differences line line.
are there existing open-source c# libraries this? if not, there variation of diff algorithm works more 2 strings?
here 2 implementations of levenshtein distance algorithm in c#
the larger result, bigger difference.
edit: copying code in case links go dead future use
example 1:
using system; /// <summary> /// contains approximate string matching /// </summary> static class levenshteindistance { /// <summary> /// compute distance between 2 strings. /// </summary> public static int compute(string s, string t) { int n = s.length; int m = t.length; int[,] d = new int[n + 1, m + 1]; // step 1 if (n == 0) { return m; } if (m == 0) { return n; } // step 2 (int = 0; <= n; d[i, 0] = i++) { } (int j = 0; j <= m; d[0, j] = j++) { } // step 3 (int = 1; <= n; i++) { //step 4 (int j = 1; j <= m; j++) { // step 5 int cost = (t[j - 1] == s[i - 1]) ? 0 : 1; // step 6 d[i, j] = math.min( math.min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); } } // step 7 return d[n, m]; } } class program { static void main() { console.writeline(levenshteindistance.compute("aunt", "ant")); console.writeline(levenshteindistance.compute("sam", "samantha")); console.writeline(levenshteindistance.compute("flomax", "volmax")); } } example 2:
public class distance { /// <summary> /// compute levenshtein distance /// </summary> /// <param name="s">string 1</param> /// <param name="t">string 2</param> /// <returns>distance between 2 strings. /// larger number, bigger difference. /// </returns> public int ld (string s, string t) { int n = s.length; //length of s int m = t.length; //length of t int[,] d = new int[n + 1, m + 1]; // matrix int cost; // cost // step 1 if(n == 0) return m; if(m == 0) return n; // step 2 for(int = 0; <= n; d[i, 0] = i++); for(int j = 0; j <= m; d[0, j] = j++); // step 3 for(int = 1; <= n;i++) { //step 4 for(int j = 1; j <= m;j++) { // step 5 cost = (t.substring(j - 1, 1) == s.substring(i - 1, 1) ? 0 : 1); // step 6 d[i, j] = system.math.min(system.math.min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); } } // step 7 return d[n, m]; }
Comments
Post a Comment