Question

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.

Was it helpful?

Solution

With D1 Phobos, you'll have to do it yourself. But it's not too hard.

bool contains(T)(T[] a, T v)
{
    foreach( e ; a )
        if( e == v )
            return true;
    return false;
}

Plus, you should be able to use it like this:

auto words = ["first"[], "second", "third"];
if( words.contains(str) ) ...

Hope that helps.

Incidentally, you can modify the above to work as an "indexOf" function:

size_t indexOf(T)(T[] a, T v)
{
    foreach( i, e ; a )
        if( e == v )
            return i;
    return a.length;
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top