#Check if string is in an array of string literals

1 messages · Page 1 of 1 (latest)

modern flame
#

I want to check if a string is equal to one of many other strings, e.g.

const str = "foo";
if (["foo", "bar", "bar"].contains(str)) {
 // Do something
} else if (["abc", "def", "ghi"].contains(str)) {
 // Do something else
} // and so on

Is there a simple way to do this without having to declare these multiple arrays of strings up front?
I was considering a for loop over an inline array of strings, but am not sure of the syntax.

tropic hamlet
#

Not particularly concise, but faster than a for loop because it can perform the comparison in O(log n) time

modern flame
#

Is there even a way to do it with a for loop with an inline array?

tropic hamlet
#

yes

#
for ([_][]const u8{ "foo", "bar", "baz" }) |x| {
    if (std.mem.eql(u8, x, str)) break true;
} else false