Find out if item is in array

4

How do I check if an item is in an 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 this?

    
asked by anonymous 18.10.2014 / 18:23

2 answers

3

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

On the other hand, maybe you just mount a loop to scan 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 discovered that it is very difficult to find official Delphi documentation. But I found some things that talk about for in .

I found another way with for normal in response in the OS . You are scanning the entire array in the same way but manually moving 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 placed GitHub for future reference.

    
18.10.2014 / 18:35
6

If you use recent versions of Delphi ( D2010 .. XE ), there is a MatchStr " who can do this work for you. However, if you use older versions of Delphi ( D6, D7 ) the AnsiMatchStr ", both functions are set in unit StrUtils .

See an example of using the MatchStr function:

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');
    
18.10.2014 / 19:18