Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking in D if a string is in array?

Tags:

arrays

d

phobos

How do I check for a string occurance in an array? I mean sure I can loop, but is there a standard function?

at first I did:

if(str in ["first", "second", "third"])

but it complained that in only works with associative arrays.

I tried to quickly lookup the phobos docs but didn't find any module related to arrays.

So is there anything, or do I just have to loop through it manually?

Edit:

I'm on D1, phobos.

like image 705
hasen Avatar asked Dec 30 '22 22:12

hasen


1 Answers

If your strings are constant (like in the example), you can use an associative array literal, but the syntax isn't pretty:

if (str in ["first"[]:0, "second":0, "third":0])

I don't think there's a library call you can use in D1's Phobos, but D2's std.algorithm has something you could use:

if (count(["first", "second", "third"][], str))

In Tango, you can use the generic contains function from tango.text.Util:

if (contains(["first", "second", "third"][], str))

Note that the [] at the end of array literals is required because we need to pass a memory slice of the static array, and not the actual static array by-value.

like image 144
Vladimir Panteleev Avatar answered Feb 02 '23 01:02

Vladimir Panteleev