On 10 Apr 2005 at 2:06, Frank Heckenbach wrote:
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?
Perhaps from some obsolete documentation?
[...]
{ 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.
[...]
That works well, thanks (and it was easy to implement a "posfrom" function for Delphi). This is (I think) the final incarnation of the function:
{ a "pos" function that matches whole words only } function PosInString (const sub : string; str : String) : Cardinal; const nSeparators = ['a'..'z', 'A'..'Z', '_', '0'..'9']; Var i, j : cardinal;
procedure findem (from : Cardinal); begin i := posfrom (sub, str, from) end;
begin PosInString := 0; If (sub = '') or (str = '') then Exit;
findem (1);
{ any match? check for whole words? } if (i = 0) then exit;
{ search for whole words } while i <> 0 do begin 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 { not found } else begin PosInString := i; exit; end; { if j <= length (str) ...} end; { if (i = 1), ... } findem (i + 1); { search again } end; { while } end;
Best regards, The Chief -------- Prof. Abimbola A. Olowofoyeku (The African Chief) web: http://www.greatchief.plus.com/