Hi
First of all, many thanks to all those who responded, and spotted the bugs!
On 9 Apr 2005 at 18:51, Frank Heckenbach wrote:
Prof A Olowofoyeku (The African Chief) wrote:
I have been trying to implement a "pos" function that only matches whole words. Below is my best effort. Is there a more efficient (or "better") way of implementing this? Thanks.
{ a "pos" function that matches whole words only } function PosInString (const sub, str : String) : Cardinal; Const nSeparators = ['a'..'z', 'A'..'Z', '0'..'9']; { non-separators }
BTW, what about the underscore?
Added.
Var i, j : Cardinal; begin result := 0;
Again, I'd strongly discourage using implicit `Result' unless absolutely necessary both syntactically and for Delphi compatibility. In this case, it's not necessary syntactically as it only appears on the LHS.
Changed.
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.
[...]
{ search for whole words only } result := i; j := length (sub) + i; if (i = 1) or ((i >1) and (Not (str [pred (i)] in nSeparators))) then begin if (j < length (str)) and (str [j] in nSeparators)
<=
(PosInString ('adam', 'adamx'))
Done.
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 then begin { dirty hack to discard processed part : any better ideas?? } for j := i to i + ( length (sub) -1 ) do str [j] := dummy; findem; { search again } end else break; end; { while }
end; { PosInString }
Best regards, The Chief -------- Prof. Abimbola A. Olowofoyeku (The African Chief) web: http://www.greatchief.plus.com/