Delphi String Handling (Removing spaces)

source : http://www.festra.com

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
inc(WordCount);
WordStarted := False;
end
else
WordStarted := not (S[CharCounter] = ‘ ‘);
end;
// Don’t forget the last word
if WordStarted then inc(WordCount);

Leave a Reply