How to find the right function in the Phobos library?

Renato Athaydes renato at athaydes.com
Sat Aug 17 08:39:47 UTC 2024


On Saturday, 17 August 2024 at 05:28:37 UTC, Bruce wrote:
> Surely D must be an indexOf function that works on
> arrays?
>
> Something like...
> string[] arr = ["pa", "db", "wb", "ha", "wa"];
> int i = arr.indexOf("ha");
>
> But, this is not satisfying.  The Phobos library should
> have this function.
>

I've noticed that you are looking for items in an array, not 
substrings in a string.

For that you can use `countUntil`:

```
import std.stdio: writeln;
import std.algorithm.searching : countUntil;

void main()
{
    const words = ["hello", "world", "bye"];

    const idx = words.countUntil("world");

    if (idx == -1)
    {
       writeln("Could not find target word");
    }
    else
    {
       writeln("Found word at index ", idx);
    }
}
```

But notice that working in D, you probably should take advantage 
of slices, as they're so powerful... `indexOf` and `countUntil` 
are normally used to find a sub-sequence you're interested in, 
which in other languages requires you to manually do based on the 
indexes... but perhaps in D you could use the very appropriately 
named `find` function to just obtain the relevant slice directly:

```
import std.stdio: writeln;
import std.algorithm.searching : find;

void main()
{
    const words = ["hello", "world", "bye"];

    const subSeq = words.find("world");

    if (subSeq.length > 0)
    {
       writeln("Found it! ", subSeq);
    }
    else
    {
       writeln("Cannot find it!");
    }
}
```

Notice that `find` returns a slice, but this is very cheap in D 
as it's just a length and a pointer to the original slice's 
array, it won't copy the array if you don't modify anything.


More information about the Digitalmars-d-learn mailing list