Find out if item is in array

How do I check if an item is in a array? Ex:

var 
Tabela : Array of String;
begin
Tabela[0] := 'Valor';
Tabela[1] := 'Value';
if Tabela[0] = 'Valor' then
// do wathever;

This would be the normal mode, but in a large array, it would take a long time to check all the numbers. How do I do that?

Author: Maniero, 2014-10-18

2 answers

Essentially doesn't have much to do, you have to check item by item. Depending on what you want there are other data structures that can minimize search time.

On the other hand, maybe what you want is just to assemble a loop to sweep the entire array with a for in:

var 
    Tabela : Array of String;
    Str : String;
begin
    Tabela[0] := 'Valor';
    Tabela[1] := 'Value';
    for Str in Tabela do
        if Str = 'Valor' then
            // do wathever;
end;

I just found that it is very difficult to find official documentation about Delphi. But I found some things that talk about for in.

I found another form with for normal in answer in SO. It is scanning all the array in the same way but manually going from index to index:

function StringInArray(const Value: string; Strings: array of string): Boolean;
var I: Integer;
begin
    Result := True;
    for I := Low(Strings) to High(Strings) do
        if Strings[i] = Value then Exit;
    Result := False;
end;

I put on GitHub for future reference.

 4
Author: Maniero, 2017-12-28 13:27:57

If you use recent versions of Delphi ( D2010.. XE ), there is the function MatchStr that can do this job for you. However, if you use older versions of Delphi (D6, D7 ) the function is usedAnsiMatchStr, both functions are defined in unit StrUtils.

See an example of using the function MatchStr:

Const
  Tabela : Array[0..4] of String = ('Valor', 'Valor1', 'Valor2', 'Valor3', 'Valor4');
begin
if MatchStr('Valor2', Tabela) then
  ShowMessage('Esse valor existe')
else
  ShowMessage('Não existe esse valor na matriz');
 6
Author: stderr, 2015-01-17 13:59:57