5

允许的字符是 A 到 Z、a 到 z、0 到 9。代码量最少或单个功能最好,因为系统对输入的响应时间很关键。

4

4 回答 4

11

如果我理解正确,您可以使用这样的函数:

function StripNonAlphaNumeric(const AValue: string): string;
var
  SrcPtr, DestPtr: PChar;
begin
  SrcPtr := PChar(AValue);
  SetLength(Result, Length(AValue));
  DestPtr := PChar(Result);
  while SrcPtr[0] <> #0 do begin
    if SrcPtr[0] in ['a'..'z', 'A'..'Z', '0'..'9'] then begin
      DestPtr[0] := SrcPtr[0];
      Inc(DestPtr);
    end;
    Inc(SrcPtr);
  end;
  SetLength(Result, DestPtr - PChar(Result));
end;

这将PChar用于最高速度(以降低可读性为代价)。

编辑:重新评论 gabr 关于使用DestPtr[0]而不是DestPtr^:无论如何这应该编译为相同的字节,但是在类似的代码中有很好的应用程序,您需要向前看。假设您想要替换换行符,那么您可以执行类似的操作

function ReplaceNewlines(const AValue: string): string;
var
  SrcPtr, DestPtr: PChar;
begin
  SrcPtr := PChar(AValue);
  SetLength(Result, Length(AValue));
  DestPtr := PChar(Result);
  while SrcPtr[0] <> #0 do begin
    if (SrcPtr[0] = #13) and (SrcPtr[1] = #10) then begin
      DestPtr[0] := '\';
      DestPtr[1] := 't';
      Inc(SrcPtr);
      Inc(DestPtr);
    end else
      DestPtr[0] := SrcPtr[0];
    Inc(SrcPtr);
    Inc(DestPtr);
  end;
  SetLength(Result, DestPtr - PChar(Result));
end;

因此我通常不使用^.

于 2009-02-22T10:05:12.613 回答
9
uses JclStrings;

  S := StrKeepChars('mystring', ['A'..'Z', 'a'..'z', '0'..'9']);
于 2009-06-08T20:38:06.267 回答
3

只是补充一句。

使用集合的解决方案在 Delphi 7 中很好,但在 Delphi 2009 中可能会导致一些问题,因为集合不能是 char(它们被转换为 ansichar)。

您可以使用的解决方案是:

case key of 
  'A'..'Z', 'a'..'z', '0'..'9' : begin end; // No action
else
  Key := #0;
end;

但最通用的方式当然是:

if not ValidChar(key) then
  Key := #0;

在这种情况下,您可以在多个位置使用 ValidChar,如果需要更改,您只需更改一次。

于 2009-02-22T10:01:39.063 回答
0

OnKeypress 事件

如果不是,则开始(键入 ['A'..'Z','a'..'z','0'..'9'])然后 Key := #0; 结尾;

于 2009-02-22T09:20:57.697 回答