(page requirements)
Downloads

Count your words

Looking for a simple function that would return the number of words, anything separated by spaces, in a specified string? Following function will do just that using pointers to strings. If you're new to string handling/parsing you might want to pay close attention to how the following function sets up a pointer to the original string and then travel through it, rather than using s[ 1 ], s[ 2 ], s[ 3 ], etc.
 
function WordsCount( s : string )
  : integer;
var
  ps       : PChar;
  nSpaces,
  n        : integer;
begin
  n  := 0;
  s  := s + #0;
  ps := @s[ 1 ];
  while( #0 <> ps^ ) do
  begin
    while((' ' = ps^)and(#0 <> ps^)) do
    begin
      inc( ps );
    end;

    nSpaces := 0;
    while((' ' <> ps^)and(#0 <> ps^))do
    begin
      inc( nSpaces );
      inc( ps );
    end;
    if ( nSpaces > 0 ) then
    begin
      inc( n );
    end;
  end;
  Result := n;
end;
Listing #1 : Delphi code. Download wrdcount (0.35 KB).
 
 
Applicable Keywords : Delphi, Delphi 1.x, Delphi 2.x, Delphi 3.x, Functions
 
 
 
Copyright © 2009 Chami.com. All Rights Reserved. | Advertise | Created in HTML Kit editor