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 CountWords(InputString: string): integer;
2. var
3.    aChar: char;
4.    WordCount: integer;
5.    IsWord: boolean;
6.    i: integer;
7. begin
8.      WordCount := 0;
9.      IsWord := False;
10.     for i := 0 to Length(InputString) do
11.     begin
12.        aChar := InputString[i];
13.       if (aChar in [
14.                   'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s',
15.                   't','u','v','w','x','y','z',
16.                   'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S',
17.                   'T','U','V','W','X','Y','Z',
18.                   '0','1','2','3','4','5','6','7','8','9','0','''','-'
19.                  ]) then
20.       begin
21.            if not IsWord then Inc(WordCount);
22.               IsWord := True;
23.       end
24.         else if aChar = '\' then IsWord := True
25.             else IsWord := False
26.
27.    end;
28.
29.    IsWord := False;
30.    Result := WordCount;
31.end;

Results:
This function will return an integer representing the number of words contained in the passed string.
Explanation:
The IsWord variable indicates whether or not the current character is part of a word. We loop through the string, looking at each character. If the current character, aChar, is contained in our list of letters and numbers, we find the character to be part of a word.
Notes:
This routine could be used to count the characters in any given string. Note that the list of characters can be modified to suit a program's specific needs.
Submission Information:
Submitted by: Urban
E-Mail: urban@scc.net



 
 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