IEl*_*ite 12 delphi parsing ascii delphi-7 delphi-2010
我需要从字符串中删除所有非标准文本characers.我需要删除所有非ascii和控制字符(换行/回车除外).
Dav*_*nan 20
而这里是Cosmin的一个变体,它只使用一次字符串,但使用了一种有效的分配模式:
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;
Run Code Online (Sandbox Code Playgroud)
Jer*_*ers 13
这样的事情应该做:
// 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;
Run Code Online (Sandbox Code Playgroud)
因为UnicodeString
你可以做类似的事情.
如果您不需要就地执行此操作,但生成该字符串的副本,请尝试此代码
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;
Run Code Online (Sandbox Code Playgroud)
并像这样使用它
s := StripCharsInSet(s,[#0..#9,#11,#12,#14..#31,#127]);
Run Code Online (Sandbox Code Playgroud)
编辑:为DEL ctrl char添加了#127.
EDIT2:这是一个更快的版本,感谢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;
Run Code Online (Sandbox Code Playgroud)