delphi - strip out all non standard text characers from string

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

    if you don't need to do it in-place, but generating a copy of the string, try this code

     type CharSet=Set of Char;
    
     function StripCharsInSet(s:string; c:CharSet):string;
      var i:Integer;
      begin
         result:='';
         for i:=1 to Length(s) do
           if not (s[i] in c) then 
             result:=result+s[i];
      end;  
    

    and use it like this

     s := StripCharsInSet(s,[#0..#9,#11,#12,#14..#31,#127]);
    

    EDIT: added #127 for DEL ctrl char.

    EDIT2: this is a faster version, thanks ldsandon

     function StripCharsInSet(s:string; c:CharSet):string;
      var i,j:Integer;
      begin
         SetLength(result,Length(s));
         j:=0;
         for i:=1 to Length(s) do
           if not (s[i] in c) then 
            begin
             inc(j);
             result[j]:=s[i];
            end;
         SetLength(result,j);
      end;  
    

提交回复
热议问题