Search code examples
stringdelphiwhitespace

How to remove all whitespace characters from a String in Delphi?


I work with Delphi XE6.

I used to use this code to remove whitespace from a string:

function RemoveWhitespace(S: string): string;
begin
  Result := StringReplace(S, ' ', '', [rfReplaceAll]);
end;

But now I realized it only removes spaces. (I had a similar problem in C#.)


Solution

  • An optimized version:

    USES System.Character;
    
    FUNCTION RemoveWhiteSpace(CONST S : STRING) : STRING;
      VAR
        I : INTEGER;
        C : CHAR;
    
      BEGIN
        SetLength(Result,LENGTH(S));
        I:=0;
        FOR C IN S DO IF NOT C.IsWhiteSpace THEN BEGIN
          INC(I);
          Result[I]:=C
        END;
        SetLength(Result,I)
      END;