Mega Code Archive

 
Categories / Delphi / Strings
 

How to get the number of words in a string

The following function can be used to get the number of words in a string. Call the function like ShowMessage(IntToStr(GetWordCount('test string, 1 2 3'))); //Function starts here function GetWordCount(const SourceStr: string): Longint; var i, len: Longint; WordSeparators: string; begin Result := 0; WordSeparators := ' ,.;'; { If needed then add more string separators } i := 1; len := Length(SourceStr); { Get the length of source string and assign to a variable } while i <= len do begin if Pos(SourceStr[i], WordSeparators) = 0 then { i.e currenct char is a valid word character like a, b, c etc. } begin { Enter a loop that will end if a word separator charcter like ., space etc. found } while (i <= len) and (Pos(SourceStr[i], WordSeparators) = 0) do Inc(i); Inc(Result); end; Inc(i); end; end;