Count the words in a text string.

Please support our Pascal and Delphi advertiser: Programming Forums - DaniWeb Sister Site
vegaseat vegaseat is offline Offline Dec 17th, 2004, 1:52 am |
0
A function that takes a string and returns the number of words in the string. An example of using pointers in Pascal.
Quick reply to this message  
Pascal and Delphi Syntax
  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.  
0
andrewgalpin andrewgalpin is offline Offline | Nov 3rd, 2009
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;
 
0
BitFarmer BitFarmer is offline Offline | Nov 11th, 2009
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.
 
 

Message:


Thread Tools Search this Thread



Tag cloud for Pascal and Delphi
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC