Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know, I can write

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

if C is an AnsiChar.

But this

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;

yields E2015: Operator not applicable to this operand type.

Is there an easy way to check if a character is contained in an array of characters (other than iterate through the array)?

like image 496
Alois Heimer Avatar asked Mar 13 '23 04:03

Alois Heimer


1 Answers

I know you don't want to, but this is one of those cases where iterating through the array really is your best option, for performance reasons:

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;

Or:

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;

Converting the input data to strings just to search it can cause huge performance bottlenecks, especially if the function is called often, such as in a loop.

like image 144
Remy Lebeau Avatar answered Apr 30 '23 07:04

Remy Lebeau