Search code examples
delphidelphi-7

How do I remove whitespace from a StringList?


I am loading a text file (which contains many lines, some containing spaces or tabs) to a StringList. How can I remove whitespace (excluding newlines) from the entire StringList?


Solution

  • Here's a crude solution that assumes that tab and space are the only white space characters:

    tmp := Strings.Text;
    tmp := StringReplace(tmp, #9, '', [rfReplaceAll]);
    tmp := StringReplace(tmp, #32, '', [rfReplaceAll]);
    Strings.Text := txt;
    

    Here's a more advanced version that will detect any whitespace:

    function RemoveWhiteSpace(const s: string): string;
    var
      i, j: Integer;
    begin
      SetLength(Result, Length(s));
      j := 0;
      for i := 1 to Length(s) do begin
        if not TCharacter.IsWhiteSpace(s[i]) then begin
          inc(j);
          Result[j] := s[i];
        end;
      end;
      SetLength(Result, j);
    end;
    ...
    Strings.Text := RemoveWhiteSpace(Strings.Text);
    

    You'll need one of the Unicode versions of Delphi and you'll need to use the Character unit.

    If you are using a non-Unicode version of Delphi then you would replace the if with:

    if not (s[i] in [#9,#32]) then begin