www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Simple string membership test

reply Ian <ian iangarcia.net> writes:
Hi,

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

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

Thanks,
  ian
Feb 15
parent reply Sergey <kornburn yandex.ru> writes:
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:

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

 Thanks,
  ian
canFind or countUntil https://dlang.org/phobos/std_algorithm_searching.html
Feb 15
parent reply Ian <ian iangarcia.net> writes:
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:

 ```d
 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.
Feb 15
parent reply Andy Valencia <dont spam.me> writes:
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
Feb 15
parent Jonathan M Davis <newsgroup.d jmdavisprog.com> writes:
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
Feb 15