4 people like it.

Diff two strings

Identify differences between two generally aligned strings.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
let DiffStrings (s1 : string) (s2 : string) =
   let s1', s2' = s1.PadRight(s2.Length), s2.PadRight(s1.Length)

   let d1, d2 = 
      (s1', s2')
      ||> Seq.zip 
      |> Seq.map (fun (c1, c2) -> if c1 = c2 then '-','-' else c1, c2)
      |> Seq.fold (fun (d1, d2) (c1, c2) -> (sprintf "%s%c" d1 c1), (sprintf "%s%c" d2 c2) ) ("","")
   d1, d2

// Example:
// > DiffStrings "The quick brown fox jumps over a lazy dog" "The quick brown fix humps over a lazy digger";;
// val it : string * string =
//   ("-----------------o--j------------------o-   ",
//    "-----------------i--h------------------i-ger")
// > 
val DiffStrings : s1:string -> s2:string -> string * string

Full name: Script.DiffStrings
val s1 : string
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
val s2 : string
val s1' : string
val s2' : string
System.String.PadRight(totalWidth: int) : string
System.String.PadRight(totalWidth: int, paddingChar: char) : string
property System.String.Length: int
val d1 : string
val d2 : string
module Seq

from Microsoft.FSharp.Collections
val zip : source1:seq<'T1> -> source2:seq<'T2> -> seq<'T1 * 'T2>

Full name: Microsoft.FSharp.Collections.Seq.zip
val map : mapping:('T -> 'U) -> source:seq<'T> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.map
val c1 : char
val c2 : char
val fold : folder:('State -> 'T -> 'State) -> state:'State -> source:seq<'T> -> 'State

Full name: Microsoft.FSharp.Collections.Seq.fold
val sprintf : format:Printf.StringFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.sprintf
Raw view New version

More information

Link:http://fssnip.net/l4
Posted:3 years ago
Author:Kit Eason
Tags: difference , strings