Get RichEdit's word count

Posted in Algorithms

Use CountInLine function which describe in a private chapter. This function carry out word count for one string only. Calling CountInLine for all lines of document, and you will get total word count of the document.

...
  private
    function CounInLine(Str: string): Integer;
...
procedure TForm1.Button1Click(Sender: TObject);
var
  CountWord, i: Integer;
begin
  CountWord:=0;
  with RichEdit1 do
  begin
    for i:=0 to Lines.Count-1 do
      CountWord:=CountWord+CountInLine(Lines.Strings[i]);
  end;
  Label1.Caption:='Word count = '+IntToStr(CountWord);
end;

function TForm1.CountInLine(Str: string): Integer;
var
  Count,Inter: Integer;
  TimeStr,Symbol: string;
begin
  Symbol:='!@#$%^&*()~[]{}":?<>,.|\/*';
  Count:=0;
  while Length(Str)>0 do
  begin
    if Pos(' ',Str)=1 then Delete(Str,1,1)
    else
    begin
      TimeStr:=Copy(Str,1,Pos(' ',Str)-1);
      try
        Inter:=StrToInt(TimeStr);
        Count:=Count-1;
      except
        on EConvertError do Count:=Count;
      end;
      if (Length(TimeStr)=1) and (Pos(TimeStr,Symbol)<>0) then 
        Count:=Count-1;
      if TimeStr='' then Str:=''
      else Delete(Str,1,Pos(' ',Str)-1);
      Count:=Count+1;
    end;
  end;
  CountInLine:=Count;
end;