Sunday字符串搜索算法Delphi实现

Sunday算法描述

这玩意儿有人实现过,作为验证再稍微美化了一下:

function PosEx(KeyStr, TextStr: string): Integer;
var
  I: Integer;
  KeyLen, BuffLen: Integer;

  function Match(N: Integer): Boolean;
  var
    J: Integer;
  begin
    Result := True;
    for J := 0 to KeyLen - 1 do
      if TextStr[J + N] <> KeyStr[J + 1] then begin
        Result := False;
        Exit;
      end;
  end;

begin
  Result := 0;
  I := 1;
  KeyLen := Length(KeyStr);
  BuffLen := Length(TextStr);
  while not Match(I) do
  begin
    if I > BuffLen then Break;
    if Pos(TextStr[I + KeyLen], KeyStr) <> 0 then begin
      I := I + 1 + KeyLen - Pos(TextStr[I + KeyLen], KeyStr);
    end else begin
      I := I + KeyLen;
    end;
  end;
  if Match(I) then
    Result := I;
end;


你可能感兴趣的:(Delphi)