The Road to Delphi

Delphi – Free Pascal – Oxygene

Whole Word Search Function in Delphi

1 Comment

To search a whole word in a string, you can use the SearchBuf function declarated in the StrUtils.pas unit .

	function SearchBuf(Buf: PAnsiChar; BufLen: Integer; SelStart: Integer; SelLength: Integer; SearchString: AnsiString; Options: TStringSearchOptions): PAnsiChar; overload;

Buf is the text buffer to search.
BufLen is the length, in chars, of Buf.
SelStart is the first character of the search when Options indicates a backward search (does not include soDown). The first character in Buf has position 0.
SelLength is the number of characters after SelStart that the search begins when Options indicates a forward search (includes soDown).
SearchString is the string to find in Buf.
Options determines whether the search runs forward (soDown) or backward from SelStart or SelStart+SelLength, whether the search is case sensitive (soMatchCase), and whether the matching string must be a whole word (soWholeWord).

If SearchBuf finds a match, it returns a pointer to the first character of the matching string in Buf. If it does not find a match, SearchBuf returns nil.

Now using this function we can construct a new  function which will return true or false if find a word in a string.

function ExistWordInString(const AString:PWideChar;const ASearchString:string;ASearchOptions: TStringSearchOptions): Boolean;
var
  Size : Integer;
begin
  Size:=StrLen(aString);
  result := SearchBuf(AString, Size, 0, 0, ASearchString, ASearchOptions)<>nil;
end;

Use it this way
Case-insensitive

  ExistWordInString('Go Delphi Go','Delphi',[soWholeWord,soDown]); //Return True
  ExistWordInString('Go Delphi, Go','Delphi',[soWholeWord,soDown]); //Return True
  ExistWordInString('Go ,Delphi, Go','Delphi',[soWholeWord,soDown]); //Return True
  ExistWordInString('Go DELPHI Go','Delphi',[soWholeWord,soDown]); //Return True

Case sensitive

  ExistWordInString('Go Delphi Go','Delphi',[soWholeWord,soDown,soMatchCase]); //Return True
  ExistWordInString('Go DELPHI Go','Delphi',[soWholeWord,soDown,soMatchCase]); //Return False
  ExistWordInString('Go DelphI Go','Delphi',[soWholeWord,soDown,soMatchCase]); //Return False

Author: Rodrigo

Just another Delphi guy.

One thought on “Whole Word Search Function in Delphi

  1. Pingback: Top 20 DAVID COOK All Right Now- GEEK 4 VOCAB! HQ | Geek or Unique

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s