+84
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
{*********** PosEx ***********}
function Posex(const substr,str:string; const startloc:integer):integer;
{Search for "substr" in "str" starting at "startloc" return 0 or the start
postion where "substr" was found}
var
i, j,k,ssLen, sLen, stop:integer;
a:char;
begin
result:=0;
ssLen:=length(substr);
slen:=length(str);
stop:=slen-sslen+1; {highest feasible start location for substring}
if (ssLen=0) or (sslen>sLen) then exit;
a:=substr[1]; {1st letter of substr}
i:=startloc; {start search location}
while (i<=stop) and (result=0) do
begin
while (i<=stop) and (a<>str[i]) do inc(i); {find the 1st letter}
if i<=stop then
begin
if sslen=1 then result:=i {It was a 1 character search, so we're done}
else
begin
j:=2;
k:=i-1; {back "K" up by 1 so that we can use K+j as the index to the string}
while (j<=sslen) do
begin {compare the rest of the substring}
if (substr[j]<>str[k+j]) then break
else inc(j); {The letter matched, go to the next+
{When we pass the substring end, "while" loop will terminate}
end;
if (j>sslen) then
begin
result:=i;
exit;
end
else inc(i); {that search failed, look for the next 1st letter match}
end;
end;
end;
end;
Несколько вложенных циклов - это НЕ может работать быстро.
Для сравнения - функция PosEx из StrUtils.pas
function PosEx(const SubStr, S: string; Offset: Cardinal = 1): Integer;
var
I,X: Integer;
Len, LenSubStr: Integer;
begin
if Offset = 1 then
Result := Pos(SubStr, S)
else
begin
I := Offset;
LenSubStr := Length(SubStr);
Len := Length(S) - LenSubStr + 1;
while I <= Len do
begin
if S[i] = SubStr[1] then
begin
X := 1;
while (X < LenSubStr) and (S[I + X] = SubStr[X + 1]) do
Inc(X);
if (X = LenSubStr) then
begin
Result := I;
exit;
end;
end;
Inc(I);
end;
Result := 0;
end;
end;
А вот что пишет автор:
The Delphi "Pos" function searches for a
substring within a string. Later versions of
Delphi also include a "PosEx" function
which
starts the search at a given position so
multiple calls can return all occurrences.
This program tests DFF versions of these
two
functions. Pos was rewritten to provide a
base
of code for PosEx. And PosEx wll provide
the
missing function for versions of Delphi
before
Delphi 7.
As an unexpected bonus, it appears that the
DFF versions of Pos and Posex are slightly
quicker than the D7 versions.
Запостил: brutushafens,
20 Апреля 2014
brutushafens 20.04.2014 19:48 # 0
bormand 20.04.2014 19:50 # +4
Смотря как вкладывать :) Сама вложенность еще ни о чем не говорит.
brutushafens 20.04.2014 19:57 # +1