I think if you have a static list of strings, I would store them in a sorted array and then use bsearch
to determine if a string is in that list. This returns NULL if it does not exist, or a pointer to the value should it exist and is probably faster than a linear search or hashing.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* cmp function for qsort and bsearch */
static int pstrcmp(const void *a, const void *b)
{
return strcmp(*(char * const *)a, *(char * const *)b);
}
/* check an input against the list of known strings */
static char *check_for_match(char *input)
{
static char *static_list[] = { "one", "two", "three", "four", "five" };
static int nelems;
/* this sorts the list, for demonstration purposes, but if the list
is static then it could be sorted prior to compiling */
if (! nelems)
{
nelems = sizeof(static_list) / sizeof(*static_list);
qsort(static_list, nelems, sizeof(*static_list), pstrcmp);
}
return bsearch(&input, static_list, nelems, sizeof(*static_list), pstrcmp);
}
int main(int argc, char *argv[])
{
if (check_for_match("should_not_match"))
{
printf("Match found.\n");
} else {
printf("No match found.\n");
}
if (check_for_match("two"))
{
printf("Match found.\n");
} else {
printf("No match found.\n");
}
return EXIT_SUCCESS;
}