文字列の途中から検索できる Pos 関数。
遅いけど多分バグはないバージョン。
function PosEx(Substr: string; S: string; P: Integer): Integer;
begin
if P <= 0 then Result := 0
else Result := Pos(Substr, Copy(S, P, Length(S)));
if Result <> 0 then Result := Result + P - 1;
end;
速いけどバグがあるかもしれないバージョン。
var
Skip: array [0..255] of Integer;
Pattern: string = '';
procedure MakeSkipTable(const SubStr: string);
var
I, J: Integer;
begin
J := Length(SubStr);
for I := 0 to 255 do Skip[I] := J;
for I := 1 to J - 1 do Skip[Ord(SubStr[I])] := J - I;
end;
function Search(const SubStr: string; const S: string; P: Integer): Integer;
var
I, J, K, M, N: Integer;
begin
Result := 0;
M := Length(SubStr);
N := Length(S);
K := M + P - 1;
while (K <= N) do
begin
I := K;
J := M;
while (J >= 1) do
begin
if S[I] <> SubStr[J] then J := -1
else
begin
Dec(I);
Dec(J);
end;
end;
if J = 0 then
begin
Result := I + 1;
Exit;
end;
Inc(K, Skip[Ord(S[K])]);
end;
end;
function PosEx(const SubStr: string; const S: string; P: Integer): Integer;
begin
if (SubStr = '') or (P <= 0) then
begin
Result := 0;
Exit;
end;
if Pattern <> SubStr then MakeSkipTable(SubStr);
Result := Search(SubStr, S, P);
end;