Best way to check for an element in an array?

FrankLike via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Apr 23 06:09:21 PDT 2014


Hi,everyone,
  It works maybe the best:

import std.stdio;

template isin(T){
     bool isin(T[] Array,T Element){
         foreach(T ArrayElement; Array){
             if(Element==ArrayElement){ return true;}
         }
     return false;
     }
}

void main(string[] args)
{
     int[] stuff=[0,1,2,3,4,5,6,7,8,9,10];

     if (stuff.isin(2))
     {
         writeln("Hello World!");
     }

	string[] strs =["Hello","world","hi","Everyone"];
	if(strs.isin("Hi"))
	{
		writeln("find Hi");
	}
	else
	{
		writeln("not find Hi from: "~strs);
	}
}

   ----------------end---------------

   Frank



More information about the Digitalmars-d-learn mailing list