Niranjan
Niranjan

Reputation: 331

google diff-match-patch library for words using c# or any backend technology

Hi I am using c# libary diff-match-patch. Here I see diff is calculated based on character level, I am looking for diff comparison at word level. Current my below code works at character level

 diff_match_patch dmp = new diff_match_patch();
 string s1 = "added";
 string s2 = "edited";
 dmp.diff_main(s1, s2);

This code do character by character comparison I am looking word by word comparison? Can someone please let me know does this library works with word by word? C# or any other backend library can someone please suggest, Any help would be appreciated. Thanks

Upvotes: 1

Views: 368

Answers (1)

Nima
Nima

Reputation: 95

You can use diff_cleanupSemantic here's the exmple from api wiki:

https://github.com/google/diff-match-patch/wiki/Language:-C%23

using DiffMatchPatch;
using System;
using System.Collections.Generic;

public class hello {
  public static void Main(string[] args) {
    diff_match_patch dmp = new diff_match_patch();
    List<Diff> diff = dmp.diff_main("Hello World.", "Goodbye World.");
    // Result: [(-1, "Hell"), (1, "G"), (0, "o"), (1, "odbye"), (0, " World.")]
    dmp.diff_cleanupSemantic(diff);
    // Result: [(-1, "Hello"), (1, "Goodbye"), (0, " World.")]
    for (int i = 0; i < diff.Count; i++) {
      Console.WriteLine(diff[i]);
    }
  }
}

Colorized output example:

diff_match_patch dmp = new diff_match_patch();
List<Diff> diff = dmp.diff_main("123 Hello World!", "12 GoodBye World");
dmp.diff_cleanupSemantic(diff);
for (int i = 0; i < diff.Count; i++)
{
    // Colorize by operation type
    switch (diff[i].operation)
    {
        case Operation.DELETE:
            Console.ForegroundColor = ConsoleColor.Red;
            break;
        case Operation.INSERT:
            Console.ForegroundColor = ConsoleColor.Green;
            break;
        case Operation.EQUAL:
            Console.ForegroundColor = ConsoleColor.White;
            break;
        default:
            break;
    }
    Console.Write(diff[i].text);
}
// back to white
Console.ForegroundColor = ConsoleColor.White;
// html code
string html = dmp.diff_prettyHtml(diff);
// result: <span>12</span><del style="background:#ffe6e6;">3 Hello</del><ins style="background:#e6ffe6;"> GoodBye</ins><span> World</span><del style="background:#ffe6e6;">!</del>

Upvotes: 1

Related Questions