Я думаю, что если у вас есть статический список строк, я бы сохранил их в отсортированном массиве, а затем использовал бы bsearch
, чтобы определить, есть ли строка в этом списке.Это возвращает NULL, если оно не существует, или указатель на значение, если оно существует, и, вероятно, быстрее, чем линейный поиск или хэширование.
#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;
}