Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 488
maxfax Avatar asked Jun 12 '11 03:06

maxfax


People also ask

How do you check if an element exists in an array?

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

How do you check a string is present in array or not in Java?

contains() method in Java is used to check whether or not a list contains a specific element. To check if an element is in an array, we first need to convert the array into an ArrayList using the asList() method and then apply the same contains() method to it​.

How do you check if a string exists in an array typescript?

Array. indexOf() Takes any value as an argument and then returns the first index at which a given element can be found in the array, or -1 if it is not present.


2 Answers

As you have found you can't check for a String in an Array of String, using in.

You could use this function instead of the if statement.

function StrInArray(const Value : String;const ArrayOfString : Array of String) : Boolean;
var
 Loop : String;
begin
  for Loop in ArrayOfString do
  begin
    if Value = Loop then
    begin
       Exit(true);
    end;
  end;
  result := false;
end;

You can call it like this.

if StrInArray(ExtString,Extensions) then

The StrUtils.pas has this already defined.

function MatchStr(const AText: string; const AValues: array of string): Boolean; 
like image 97
Robert Love Avatar answered Sep 21 '22 18:09

Robert Love


Initialise a TStringList instance from the constant array and use IndexOf().

like image 22
Misha Avatar answered Sep 18 '22 18:09

Misha