delphi - strip out all non standard text characers from string

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

    Something like this should do:

    // For those who need a disclaimer: 
    // This code is meant as a sample to show you how the basic check for non-ASCII characters goes
    // It will give low performance with long strings that are called often.
    // Use a TStringBuilder, or SetLength & Integer loop index to optimize.
    // If you need really optimized code, pass this on to the FastCode people.
    function StripNonAsciiExceptCRLF(const Value: AnsiString): AnsiString;
    var
      AnsiCh: AnsiChar;
    begin
      for AnsiCh in Value do
        if (AnsiCh >= #32) and (AnsiCh <= #127) and (AnsiCh <> #13) and (AnsiCh <> #10) then
          Result := Result + AnsiCh;
    end;
    

    For UnicodeString you can do something similar.

提交回复
热议问题