On Sat, Apr 09, 2005 at 05:14:26PM +0100, Prof A Olowofoyeku (The African Chief) wrote:
Hi
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.
Efficiency is not a problem, but correctness: PosInString ('adam','adamant adam') gives 0 instead of 9.
Emil Jerabek
{ 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 } Var i, j : Cardinal; begin result := 0; If (sub = '') or (str = '') then Exit; i := pos (sub, str);
{ any match? } if (i = 0) then exit;
{ 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) then result := 0; end else result := 0; end;
{ test: correct results in comments } begin writeln (PosInString ('adam', 'he is adamant')); {0} writeln (PosInString ('adam', 'why is he so adamant about it?')); {0} writeln (PosInString ('adam', 'he knows about adam ant')); {16} writeln (PosInString ('adam', 'adam and eve')); {1} writeln (PosInString ('adam', 'eve and adam')); {9} writeln (PosInString ('adam', 'eve and adam ate the apple')); {9} end.
Best regards, The Chief
Prof. Abimbola A. Olowofoyeku (The African Chief) web: http://www.greatchief.plus.com/