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?
I'm on D1, phobos.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With