Mega Code Archive

 
Categories / Delphi / Strings
 

How to count the number of words in a string

Title: How to count the number of words in a string function Seps(As_Arg: Char): Boolean; begin Seps := As_Arg in [#0..#$1F, ' ', '.', ',', '?', ':', ';', '(', ')', '/', '\']; end; function WordCount(CText: string): Longint; var Ix: Word; Work_Count: Longint; begin Work_Count := 0; Ix := 1; while Ix = Length(CText) do begin while (Ix = Length(CText)) and (Seps(CText[Ix])) do Inc(Ix); if Ix = Length(CText) then begin Inc(Work_Count); while (Ix = Length(CText)) and (not Seps(CText[Ix])) do Inc(Ix); end; end; Word_Count := Work_Count; end; To count the number opf words in a TMemo Component, call: WordCount(Memo1.Text)