Search code examples
arraysdphobos

Checking in D if a string is in array?


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.


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;
    }