unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Edit2: TEdit;
procedure Button1Click(Sender: TObject);
private
public
function mypos(SubStr: string; MainStr: string): integer;
end;
var
Form1: TForm1;
implementation{$R *.dfm}
function TForm1.mypos(SubStr: string; MainStr: string): integer;
var
StrNext: array of integer;
i, j: integer;
procedure get_next(SubStr: string);
var
tj, tk: integer;
begin
tj := 1; tk := 0;
while tj < Length(SubStr) do
begin
if (tk = 0) or (SubStr[tj] = SubStr[tk]) then
begin
tj := tj + 1; tk := tk + 1;
StrNext[tj] := tk;
end
else tk := StrNext[tk];
end;
end;
begin
SetLength(StrNext, Length(SubStr) + 1);
get_next(SubStr);
Result := 0;
i := 1; j := 1;
while (i <= Length(MainStr)) and (j <= Length(SubStr)) do
begin
if (j = 0) or (MainStr[i] = SubStr[j]) then
begin
i := i + 1; j := j + 1;
end
else j := StrNext[j]; if j > Length(SubStr) then Result := i - Length(SubStr);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(IntToStr(mypos(Edit1.text, Edit2.text)));
end;
end.
Function myPos(SubStr, MainStr: String): Integer; Var
i, j, k, m, n: Integer;
skip: Array[0..255] Of Integer;
Begin
m := Length(SubStr);
n := Length(MainStr);
If (m = 0) Or (n = 0) Then
Begin
Result := 0;
Exit;
End;
For k := 0 To 255 Do
skip[k] := m; For k := 1 To m - 1 Do
skip[Ord(SubStr[k])] := m - k;
Result := 0;
k := m;
While (k <= n) Do
Begin
i := k;
j := m;
While (j >= 1) Do
If MainStr[i] <> SubStr[j] Then
j := -1
Else
Begin
Dec(j);
Dec(i);
End;
If j = 0 Then
Begin
Result := i + 1;
Exit;
End;
Inc(k, skip[Ord(MainStr[k])]);
End;
End;
|
请发表评论