您可以简单地检查字符串数组中是否存在字符串。更好的解决方案可能是实际返回字符串:
/*
* haystack: The array of strings to search.
* needle: The string to find.
* max: The number of strings to search in "haystack".
*/
char *
string_find(char **haystack, char *needle, size_t max)
{
char **end = haystack + max;
for (; haystack != end; ++haystack)
if (strcmp(*haystack, needle) == 0)
return *haystack;
return NULL;
}
如果您想要一个集合的行为,其中数组中的所有字符串都是唯一的,那么您可以这样使用它:
typedef struct set_strings {
char **s_arr;
size_t count;
size_t max;
} StringSet;
.
.
.
int
StringSet_add(StringSet *set, const char *str)
{
// If string exists already, the add operation is "successful".
if (string_find(set->s_arr, str, set->count))
return 1;
// Add string to set and return success if possible.
/*
* Code to add string to StringSet would go here.
*/
return 1;
}
如果你想对字符串做一些实际的事情,你也可以这样使用它:
/*
* Reverse the characters of a string.
*
* str: The string to reverse.
* n: The number of characters to reverse.
*/
void
reverse_str(char *str, size_t n)
{
char c;
char *end;
for (end = str + n; str < --end; ++str) {
c = *str;
*str = *end;
*end = c;
}
}
.
.
.
char *found = string_find(words, word, word_count);
if (found)
reverse_str(found, strlen(found));
作为一种通用算法,这是相当有用的,甚至可以根据需要应用于其他数据类型(当然需要进行一些返工)。正如undefined behaviour's answer 所指出的,它在大量字符串上不会很快,但对于简单和小型的东西来说已经足够了。
如果您需要更快的东西,该答案中给出的建议很好。如果您自己编写代码,并且能够保持排序,那么这样做是个好主意。这允许您使用比线性搜索更好的搜索算法。标准bsearch 很棒,但是如果您想要适合快速插入的东西,您可能需要一个搜索例程,为您提供插入新项目的位置,以避免在bsearch 返回@ 之后搜索位置987654327@。换句话说,既然你可以搜索一次并完成同样的事情,为什么还要搜索两次呢?