How can I compute a difference between two strings?

前端 未结 2 756
难免孤独
难免孤独 2020-12-30 08:32

I want to create a function in Delphi that computes different levels of two strings. If two strings are equal (ignoring case), then it should return 0, but if they are not e

2条回答
  •  滥情空心
    2020-12-30 08:57

    What you want is known as the Levenshtein distance (the minimum number of edits to transform one string into the other, where an edit is either a character insertion, character deletion or character substitution). The wikipedia site has a pseudo code implementation.

    Delphi implementation:

    function LevenshteinDistance(String1 : String; String2 : String) : Integer;
    
    var
      Length1, Length2      : Integer;
      WorkMatrix            : array of array of Integer;
      I, J                  : Integer;
      Cost                  : Integer;
      Val1, Val2, Val3      : Integer;
    
    begin
    String1 := TCharacter.ToUpper (String1);
    String2 := TCharacter.ToUpper (String2);
    Length1 := Length (String1);
    Length2 := Length (String2);
    SetLength (WorkMatrix, Length1+1, Length2+1);
    for I := 0 to Length1 do
      WorkMatrix [I, 0] := I;
    for J := 0 to Length2 do
      WorkMatrix [0, J] := J;
    for I := 1 to Length1 do
      for J := 1 to Length2 do
        begin
        if (String1 [I] = String2 [J]) then
          Cost := 0
        else
          Cost := 1;
        Val1 := WorkMatrix [I-1, J] + 1;
        Val2 := WorkMatrix [I, J-1] + 1;
        Val3 := WorkMatrix[I-1, J-1] + Cost;
        if (Val1 < Val2) then
          if (Val1 < Val3) then
            WorkMatrix [I, J] := Val1
          else
            WorkMatrix [I, J] := Val3
        else
          if (Val2 < Val3) then
            WorkMatrix [I, J] := Val2
          else
            WorkMatrix [I, J] := Val3;
        end;
    Result := WorkMatrix [Length1, Length2];
    end;
    

提交回复
热议问题