Rather than scanning a string with (e.g. strchr et. al.), if you're doing this a lot and you have more chars in your "set", you could use a translation table.
The initialization may seem a bit cumbersome, but it would be very fast to execute.
char list[256] = {
['a'] = 1,
['d'] = 1,
['i'] = 1,
['k'] = 1,
};
int
match(int letter)
{
return list[(unsigned char) letter];
}
A more general way may be to initialize the table once from a string.
char list[256];
void
init(char *list,const char *str)
{
memset(list,0,256);
for (; *str != 0; ++str)
list[(unsigned char) *str] = 1;
}
int
match(int letter)
{
return list[(unsigned char) letter];
}
int
main(void)
{
init(list,"adik");
// ...
}
UPDATE:
thanks, could you explain this initialization a bit more? char list[256] = { ['a'] = 1, ['d'] = 1,...} ? I've never seen that notation before.
It's what's called a "designated initializer".
There are two types: one for arrays, and one for structs. They have different syntax.
Normal initializers are "positional".
With any initializer, any position that is not explicitly initialized gets a value of 0.
One of the key features is that designated initializers can appear in any order, unlike positional ones.
Since you have python experience, they are [particularly for the struct variants], similar/analogous to keyword arguments in python function calls.
Arrays:
For example, ['a'] = 1 statically initializes the array element just as if you had done (in executable code): list['a'] = 1;
These are equivalent:
int arr[10] = { 0, 0, 0, 0, 7, 0, 0, 0, 0, 0 };
int arr[10] = { 0, 0, 0, 0, 7 };
int arr[10] = { [4] = 7 };
And, these:
int arr[10] = { 0, 0, 0, 0, 7, 6, 0, 0, 0, 0 };
int arr[10] = { 0, 0, 0, 0, 7, 6 };
int arr[10] = { [5] = 6, [4] = 7 };
Structs:
The initializer syntax is:
.sym = value
Here's an example:
struct foo {
int x;
int y;
const char *z;
};
struct foo str1 = { 0, 23, "hello" };
struct foo str2 = { .z = "hello", .y = 23 };
Combinations:
We can combine/intersperse these for more complex scenarios:
struct foo {
int x;
int y;
const char *z;
};
struct bar {
int j;
const char *k;
};
struct joint {
struct foo j_foo[3];
struct bar j_bar[4];
const char *jname;
};
struct joint jlist[6] = {
[3] = {
.jname = "jlist[3]",
.j_bar = {
[2] = { .j = 19, .k = "jbar2" },
[0] = { .j = 62 },
},
.j_foo = {
[1] = { .y = 37, .z = "jfoo1" },
[0] = { .y = 17 },
},
},
};