Author: Stewart Moss
Does anyone know of a function that finds a whole word within a string as in the
search and replace options?
Answer:
1 2 {Function FindWord3 4 Parameters:5 pattern: word to search for6 text: text to search7 caseSensitive: determines whether search is case sensitive or not. Default is not 8 case-sensitive.9 startAt: first character to search, default is 1.10 11 Returns:12 The start of the first instance of the word, or 0, if the word was not found or 13 only as part of larger words. A word in this context is any sequence of 14 alphanumeric characters delimited by non-alphanumeric characters.15 16 Error Conditions: none17 18 Created: 18.05.99 by P. Below}19 20 function FindWord(pattern, text: string; caseSensitive: Boolean = false; startAt:
21 Integer = 1): Integer;
22 var23 offset, endOfPattern: Integer;
24 begin25 Result := 0;
26 if Length(text) = 0 then27 exit;
28 if Length(pattern) = 0 then29 begin30 {By definition a pattern of length 0 is always found}31 result := 1;
32 Exit;
33 end;
34 ifnot caseSensitive then35 begin36 pattern := AnsiLowerCase(pattern);
37 text := AnsiLowerCase(text);
38 end;
39 endOfPattern := startAt + Length(pattern);
40 for offset := startAt to Length(text) - Length(pattern) + 1 do41 begin42 if pattern[1] = text[offset] then43 begin44 if ((offset = 1) ornot IsCharAlphaNumeric(text[offset - 1])) and45 ((endOfPattern
46 > Length(text)) ornot IsCharAlphaNumeric(text[endOfPattern]))
47 and (StrLComp(@text[offset], @pattern[1], Length(pattern)) = 0) then48 begin49 Result := offset;
50 exit;
51 end;
52 end;
53 Inc(endOfPattern);
54 end;
55 end;