943,510 Members | Top Members by Rank

Ad:
0

Count the words in a text string.

by on Dec 17th, 2004
A function that takes a string and returns the number of words in the string. An example of using pointers in Pascal.
Pascal and Delphi Code Snippet (Toggle Plain Text)
  1. // count words in a string using pointers
  2. // Pascal code used in a Delphi 3.0 program
  3.  
  4. function WordsCount(s: string ): integer;
  5. var
  6. ps: PChar;
  7. nSpaces, n: integer;
  8. begin
  9. n := 0;
  10. // make it a string that ends with value zero
  11. s := s + #0;
  12. // point to start of string s
  13. ps := @s[ 1 ];
  14. // keep loop going up to zero ending
  15. while( #0 <> ps^ ) do
  16. begin
  17. // checks for space = ' '
  18. while((' ' = ps^) and (#0 <> ps^)) do
  19. begin
  20. inc( ps );
  21. end;
  22. nSpaces := 0;
  23. while((' ' <> ps^) and (#0 <> ps^)) do
  24. begin
  25. inc(nSpaces);
  26. inc(ps);
  27. end;
  28. if (nSpaces > 0) then
  29. begin
  30. inc( n );
  31. end;
  32. end;
  33. Result := n;
  34. end;
  35.  
Comments on this Code Snippet
Nov 3rd, 2009
0

Re: Count the words in a text string.

Or you could use this function:
Pascal and Delphi Syntax (Toggle Plain Text)
  1. function WordCount (s: string): integer;
  2.  
  3. var
  4. i, count : integer;
  5. letter : string;
  6. begin
  7. count := 1;
  8. for I := 1 to length(s) do
  9. begin
  10. letter := s[i];
  11.  
  12. if letter = ' ' then count := count +1;
  13. end;
  14. result := count;
  15. end;
Newbie Poster
andrewgalpin is offline Offline
1 posts
since Nov 2009
Nov 11th, 2009
0

Re: Count the words in a text string.

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.
Junior Poster in Training
BitFarmer is offline Offline
51 posts
since Nov 2009
Message:
Previous Thread in Pascal and Delphi Forum Timeline: Dataset
Next Thread in Pascal and Delphi Forum Timeline: Using Media Player





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC