tags:

views:

148

answers:

2

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.

+4  A: 

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.

CyberShadow
+4  A: 

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;
}
DK
That's what I ended up doing, except I called it "in_array" instead of contains, and I put the item as the first parameter, but your ways is nicer in that it can be used as a property. How come they didn't put something that simple in phobos?
hasen j
Same reason a lot of things aren't in Phobos: no one has the time or inclination. Plus, everyone is working on Phobos2 for D 2.0.
DK
Walter is actually against having 'in' work on arrays in the way the questioner expected it to. Reason: 'in' for assoc arrays tells you if the key is present. So he argues 'in' for an array should also check if the 'key' is present would be an element index, not the value. So he thinks it would be too inconsistent to have it do the obvious thing.
Baxissimo