Thread overview
Simple string membership test
Feb 15
Ian
Feb 15
Sergey
Feb 15
Ian
February 15

Hi,

What's the best (idiomatic) way of checking if a string is in a list of strings:

string v = "tofind";
if (v ismemberof ["abc", "def","tofind"])
   etc();

Thanks,
ian

February 15

On Saturday, 15 February 2025 at 17:58:44 UTC, Ian wrote:

>

Hi,

What's the best (idiomatic) way of checking if a string is in a list of strings:

string v = "tofind";
if (v ismemberof ["abc", "def","tofind"])
   etc();

Thanks,
ian

canFind or countUntil
https://dlang.org/phobos/std_algorithm_searching.html

February 15

On Saturday, 15 February 2025 at 18:13:39 UTC, Sergey wrote:

>

On Saturday, 15 February 2025 at 17:58:44 UTC, Ian wrote:

>

Hi,

What's the best (idiomatic) way of checking if a string is in a list of strings:

string v = "tofind";
if (v ismemberof ["abc", "def","tofind"])
   etc();

Thanks,
ian

canFind or countUntil
https://dlang.org/phobos/std_algorithm_searching.html

canFind is Perfect. Thank you.

February 16

On Saturday, 15 February 2025 at 19:27:19 UTC, Ian wrote:

>

canFind is Perfect. Thank you.

If performance is an issue, putting them as keys in an Associative Array and simply using "in" should scale nicely to even very large numbers of strings to search.

Andy

February 15
On Saturday, February 15, 2025 9:33:06 PM MST Andy Valencia via Digitalmars-d-learn wrote:
> On Saturday, 15 February 2025 at 19:27:19 UTC, Ian wrote:
> > canFind is Perfect. Thank you.
>
> If performance is an issue, putting them as keys in an Associative Array and simply using "in" should scale nicely to even very large numbers of strings to search.

It can, but unless your array is large, the odds are very high that simply doing a linear search with find or canFind will be faster. It avoids allocating anything on the heap, and the CPU tends to be much faster when operating on arrays. So, while the AA approach will likely be faster if the array is long enough, your array is likely going to need to be pretty long before building an AA just to find a single element is going to be faster - though if you're searching for a bunch of different elements rather than just one, it could make the AA approach faster. So, ultimately, benchmarking with your particular data set would be required to know for sure which would be faster, but for a single search, the AA will probably lose.

- Jonathan M Davis