Re: Delphi String Handling (Removing spaces)

Posted by Bill on June 27, 2006

In Reply to Delphi String Handling (Removing spaces) posted by Nokoff on June 19, 2006

: Hi there, I am currently trying to figure out how to correct an error in a program I currently have. The program's function is to count the number of words in a string.

: Currently, TForm1.Button1Click correctly displays the amount of words by counting the amount of spaces and adding one to that counter. HOWEVER, does not function correctly if there is more than one space between the words or at the beginning of the sentence. Is there any snippet of code i can whip in here to correct this?

Instead of counting the spaces, try this:

Count each non-spaces substring as a word, if it is followed by a space, or if it comes at the end of the string. With this rule, you don't have to worry about multiple, leading nor trailing spaces :)

Delphi 7 code example:

suppose your string is in variable S, WordCount and CharCounter are integers, WordStarted is a Boolean variable.

WordCount := 0;
WordStarted := False;
for CharCounter := 1 to Length(S) do begin
  if WordStarted and (S[CharCounter] = ' ') then begin
    WordStarted := False;
    WordStarted := not (S[CharCounter] = ' ');
// Don't forget the last word
if WordStarted then inc(WordCount);


Related Articles and Replies





DelphiLand Club members: enter your Membership password.
Guests can get a Forum Guest password by subscribing to the DelphiLand Newsletter.