Prof A Olowofoyeku (The African Chief) wrote:
If (sub = '') or (str = '') then Exit;
BTW, `Pos' returns 1 if the substring is empty (meaning that an empty string matches anywhere).
But BP and Delphi (all versions) return 0. So there is an incompatibility here.
I had thought they also returned 1. Where did I get that from?
Any comments on the revised version (below)? Thanks.
{ a "pos" function that matches whole words only } function PosInString (const sub : String; str : String) : Cardinal; const dummy = #0; nSeparators = ['a'..'z', 'A'..'Z', '_', dummy, '0'..'9'];
Var i, j : cardinal; notfound : boolean;
procedure findem; begin i := pos (sub, str) end;
begin PosInString := 0; If (sub = '') or (str = '') then Exit;
findem;
{ any match? check for whole words? } if (i = 0) then exit;
{ searching for whole words } while i <> 0 do begin notfound := false; j := length (sub) + i; if (i = 1) or ((i > 1) and (Not (str [i-1] in nSeparators))) then begin if (j <= length (str)) and (str [j] in nSeparators) then notfound := true else begin PosInString := i; exit; end; { if j < length (str) ...} end { if i = i, ... } else notfound := true;
if notfound
BTW, notfound will always be True here as you use Exit otherwise.
then begin { dirty hack to discard processed part : any better ideas?? } for j := i to i + ( length (sub) -1 ) do str [j] := dummy;
In fact this method is not reliable (PosInString ('aa-a', 'aa-aa-a')).
A better (and possibly faster) method is, as I said, to use `PosFrom' (non-standard) or `Pos' applied to a substring, both in order to search only after the position of the last match.
Set i := 0 before the loop and search from position i + 1 at the start of the loop (will also avoid the need for a subroutine).
findem; { search again } end else break;
end; { while }
end; { PosInString }
Frank