delphi - strip out all non standard text characers from string

前端 未结 6 1377
-上瘾入骨i
-上瘾入骨i 2021-02-13 14:52

I need to strip out all non standard text characers from a string. I need remove all non ascii and control characters (except line feeds/carriage returns).

6条回答
  •  暖寄归人
    2021-02-13 15:24

    And here's a variant of Cosmin's that only walks the string once, but uses an efficient allocation pattern:

    function StrippedOfNonAscii(const s: string): string;
    var
      i, Count: Integer;
    begin
      SetLength(Result, Length(s));
      Count := 0;
      for i := 1 to Length(s) do begin
        if ((s[i] >= #32) and (s[i] <= #127)) or (s[i] in [#10, #13]) then begin
          inc(Count);
          Result[Count] := s[i];
        end;
      end;
      SetLength(Result, Count);
    end;
    

提交回复
热议问题