How do I check whether a string exists in an array?

Viewed 37073

I have this code:

var
  ExtString: string;
const
  Extensions : array[0..4] of string = ('.rar', '.zip', '.doc', '.jpg', '.gif');

if ExtString in Extensions then

On the last line, I get an error:

[DCC Error] E2015 Operator ('then') not applicable to this operand type

I think I can not do this, so how can I properly perform my task?

4 Answers

You can use the funcions IndexStr (case sensitive) or IndexText (case insensitive) from System.StrUtils to find the string inside the array and retrive the index.

var
  ExtString: string;
const
  Extensions : array[0..4] of string = ('.rar', '.zip', '.doc', '.jpg', '.gif');
begin
  if (IndexStr(ExtString, Extensions) <> -1) then
    ShowMessage('Finded')
  else
    ShowMessage('Not finded');

Link to help in docwiki from embarcadero.

Sometimes the simplest solutions aren't the most obvious

var
  ExtString: string;
const
  Extensions = ('.rar,.zip,.doc,.jpg,.gif');

if Pos(ExtString, Extensions) > 0 then

or with .Netrification in the new StrUtils library, which I love!!! Think Helpers!

if Extensions.IndexOf(ExtString) > -1 then

or you can loop through an array using .Split(',')

Related