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
Thread overview | |||||||
---|---|---|---|---|---|---|---|
|
February 15 Simple string membership test | ||||
---|---|---|---|---|
| ||||
Hi, What's the best (idiomatic) way of checking if a string is in a list of strings:
Thanks, |
February 15 Re: Simple string membership test | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ian | 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:
Thanks, canFind or countUntil |
February 15 Re: Simple string membership test | ||||
---|---|---|---|---|
| ||||
Posted in reply to Sergey | 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:
Thanks, canFind or countUntil canFind is Perfect. Thank you. |
February 16 Re: Simple string membership test | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ian | 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 Re: Simple string membership test | ||||
---|---|---|---|---|
| ||||
Posted in reply to Andy Valencia | 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
|