Delphi32.com - Home!
| Home/News | Downloads | Forums | D32 Magazine | Resources | Info and Facts |  
 
 Count Words in a String


The following information applies to:
  • Delphi (All Versions)
Steps, Assumptions, Procedures:
  1. Uses Windows.pas
  2. Uses System.pas
Code:

1. function WordCount(Sentence: string):integer;
2. var
3.    Words: integer;
4. begin
5.    if Sentence <> '' then
6.    begin
7.      Words:=1;
8.      while Pos(' ',Sentence)<> 0 do
9.      begin
10.        Delete(Sentence,1,Pos(' ',Sentence));
11.        Inc(Words);
12.     end;
13.     WordCount:=Words
14.   end
15.   else
16.    WordCount:=0;
17. end;

Results:
This function will return an integer representing the number of words contained in the passed string.
Explanation:
//Uses Pascal built in functions Length, Pos and Delete.
//Sentence is a Val param because it gets mutated.
//The loop condition consist of checking for a space in the sentence
//0 is reterned from Pos if there is no spaces.
//While there is spaces delete Sentece starting at 1 to the first
//occurence of a space. After every word delete add one to words.
Notes:
This routine could be used to count the characters in any given string.
Submission Information:
Submitted by: Ross Bush
E-Mail: rossbush@mindspring.com



 
 Hits/month  2,500,000+ 
 Downloads
 (Since May 2000)
 7,393,709 
 Total Files  6,023 
 Forum msgs  7,670 
 Articles/FAQs  70+/900+ 
Kylix
Tips n Tricks
FAQs
Knowledge Base
Bug Listings
Articles
Books
Newsgroups
Links
Submissions
Testimonials
Advertising
Contact Us
About Us
Search Amazon:
Top Selling Software at Amazon

| Home/News | Downloads | Forums | Resources | Info and Facts | Testimonials |
  Site Search:
 


Comments/Problems: Webmaster@delphi32.com
Copyright © 1998-2006, Delphi32.com. All rights reserved.
Terms of Use