delphi - strip out all non standard text characers from string

前端 未结 6 1396
-上瘾入骨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:35

    Here's a version that doesn't build the string by appending char-by-char, but allocates the whole string in one go. It requires going over the string twice, once to count the "good" char, once to effectively copy those chars, but it's worth it because it doesn't do multiple reallocations:

    function StripNonAscii(s:string):string;
    var Count, i:Integer;
    begin
      Count := 0;
      for i:=1 to Length(s) do
        if ((s[i] >= #32) and (s[i] <= #127)) or (s[i] in [#10, #13]) then
          Inc(Count);
      if Count = Length(s) then
        Result := s // No characters need to be removed, return the original string (no mem allocation!)
      else
        begin
          SetLength(Result, Count);
          Count := 1;
          for i:=1 to Length(s) do
            if ((s[i] >= #32) and (s[i] <= #127)) or (s[i] in [#10, #13]) then
            begin
              Result[Count] := s[i];
              Inc(Count);
            end;
        end;
    end;
    

提交回复
热议问题