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

Best way to check if a character is contained in an array of char

我知道,我会写

if C in ['#', ';'] then ...

如果 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;

产量 E2015: Operator not applicable to this operand type

有没有简单的方法来检查一个字符是否包含在字符数组中(而不是遍历数组)?

如果试图避免遍历数组并且如果速度无关紧要那么IndexOfAny可能会有所帮助:

function CheckValid(C: Char; const Invalid: array of Char; OtherParams: TMyParams): Boolean;
begin
    Result := string(C).IndexOfAny(Invalid) >= 0;
    //maybe other test...
    //....
end;

来自 Delphi 文档:

[IndexOfAny r]eturns an integer indicating the position of the first given character found in the 0-based string. [It returns -1 if the character is not found.]

如果关注速度,这应该避免,正如@RemyLebeau 在评论中解释的那样:

Casting C to String to call IndexOfAny() will create 1 temp String. [...] if CheckValid() is called often, those conversions can be a BIG performance bottleneck, not to mention a waste of memory.

在这种情况下,@RemyLebeau 的回答是更好的解决方案。

我知道你不想这样做,但出于性能原因,这是迭代数组确实是你最好的选择的情况之一:

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;

或者:

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;

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