Find out if item is in array

Asked

Viewed 12,692 times

6

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;

That would be the normal way, but in a array great, it would take too long to check all the numbers. How do I do this?

2 answers

6

If you use recent versions of Delphi(D2010.. XE), there is the function MatchStr that can do this work for you. However, if you use older versions of Delphi(D6, D7) the function is used AnsiMatchStr, 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');

4


Essentially you don’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 the search time.

On the other hand, maybe what you want is just to ride one loop to sweep the whole 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 out that it is very difficult to find official documentation about Delphi. But I found some things that talk about the for in.

I found another way with for normal in response in the OS. It’s sweeping the whole array similarly 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 in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.