954,529 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Count the words in a text string.

0
By vegaseat on Dec 17th, 2004 11:52 am

A function that takes a string and returns the number of words in the string. An example of using pointers in Pascal.

// count words in a string using pointers
// Pascal code used in a Delphi 3.0 program

function WordsCount(s: string ): integer;
var
  ps: PChar;
  nSpaces, n: integer;
begin
  n := 0;
  // make it a string that ends with value zero
  s := s + #0;
  // point to start of string s
  ps := @s[ 1 ];
  // keep loop going up to zero ending
  while( #0 <> ps^ ) do
  begin
    // checks for space = ' '
    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;

Or you could use this function:

function WordCount (s: string): integer;

var
i, count : integer;
letter : string;
begin
   count := 1;
for I := 1 to length(s) do
 begin
   letter := s[i];

   if letter = ' ' then count := count +1;
   end;
   result := count;
end;
andrewgalpin
Newbie Poster
1 post since Nov 2009
Reputation Points: 10
Solved Threads: 0
 

andrewgalpin: your code count SPACES, not words... try it out with this text "hello bye", you won't get a 2, instead you will get the spaces between words... is NOT the same, and if you try to detect "first space" from "subsecuent spaces", then you end up with the original code, but several times slower if don't use pointewrs.

BitFarmer
Junior Poster in Training
51 posts since Nov 2009
Reputation Points: 12
Solved Threads: 5
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You