检查字符是否包含在char数组中的最佳方法

Alo*_*mer 4 delphi delphi-xe4

我知道,我可以写

if C in ['#', ';'] then ...
Run Code Online (Sandbox Code Playgroud)

如果CAnsiChar.

但是这个

function CheckValid(C: Char; const Invalid: array of Char; OtherParams: TMyParams): Boolean;
begin
    Result := C in Invalid;    // <-- Error because Invalid is an array not a set
    //maybe other tests...
    //Result := Result and OtherTestsOn(OtherParams);
end;
Run Code Online (Sandbox Code Playgroud)

收益率E2015: Operator not applicable to this operand type.

有没有一种简单的方法可以检查字符是否包含在字符数组中(除了遍历数组)?

Rem*_*eau 7

我知道你不想这样做,但这是其中一个例子,因为性能原因,迭代数组确实是你最好的选择:

function CheckValid(C: Char; const Invalid: array of Char): Boolean;
var
  I: Integer;
begin
  Result := False;
  for I := Low(Invalid) to High(Invalid) do begin
    if Invalid[I] = C then begin
      Result = True;
      Exit;
    end;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

要么:

function CheckValid(C: Char; const Invalid: array of Char): Boolean;
var
  Ch: Char;
begin
  Result := False;
  for Ch in Invalid do begin
    if Ch = C then begin
      Result = True;
      Exit;
    end;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

将输入数据转换为字符串只是为了搜索它可能会导致巨大的性能瓶颈,尤其是在经常调用该函数时,例如在循环中.