Mirror

Count the number of words in a string (Views: 711)

Problem/Question/Abstract:

How to count the number of words in a string

Answer:

{ ... }
type
TCharSet = TSysCharSet;
{ ... }

function WordCount(const S: string; const WordDelims: TCharSet): Integer;
var
SLen, I: Cardinal;
begin
Result := 0;
I := 1;
SLen := Length(S);
while I <= SLen do
begin
while (I <= SLen) and (S[I] in WordDelims) do
Inc(I);
if I <= SLen then
Inc(Result);
while (I <= SLen) and not (S[I] in WordDelims) do
Inc(I);
end;
end;

Use the following statement to call the function:

WordCount(Edit1.Text, [' ', ','])


<< Back to main page