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.
  • Re: How to find ... monkyyy via Digitalmars-d-learn
    • Re: How to ... Bruce via Digitalmars-d-learn
    • Re: How to ... Ron Tarrant via Digitalmars-d-learn
    • Re: How to ... Renato Athaydes via Digitalmars-d-learn
    • Re: How to ... Lance Bachmeier via Digitalmars-d-learn
    • Re: How to ... Steven Schveighoffer via Digitalmars-d-learn
      • Re: How... Vinod K Chandran via Digitalmars-d-learn
        • Re:... Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
          • ... Vinod K Chandran via Digitalmars-d-learn
        • Re:... IchorDev via Digitalmars-d-learn
          • ... Vinod K Chandran via Digitalmars-d-learn
      • Re: How... Ron Tarrant via Digitalmars-d-learn
        • Re:... Renato Athaydes via Digitalmars-d-learn
      • Re: How... Andy Valencia via Digitalmars-d-learn

Reply via email to