確かstrstr
に、他の文字列で最初に出現する部分文字列を見つけるC標準ライブラリの機能があります。s
それが文字列へのポインタであると仮定しましょう。
if (strstr(*s, "MyString") != NULL) {
/* found */
} else {
/* not found */
}
が文字列の配列である場合s
は、配列を実行し、現在の文字列とサブ文字列を。と比較する必要がありますstrstr
。
#include <stddef.h>
#include <string.h>
int
f(char const **p, char const *q, size_t nmemb)
{
for (size_t i = 0; i < nmemb; ++i)
if (strstr(p[i], q) != NULL)
return 1;
return 0;
}
すべての文字列のサイズが同じである場合は、実際にを使用できますstrcmp
。
#include <stddef.h>
#include <string.h>
int
f(char const **p, char const *q, size_t nmemb, size_t size)
{
for (size_t i = 0; i < nmemb; ++i)
if (strncmp(p[i], q, size) == 0)
return 1;
return 0;
}
もう1つの解決策は、配列を並べ替えてから、要素を検索することです。
#include <stddef.h>
#include <stdlib.h>
static int
cmp(void const *p, void const *q)
{
return strcmp((char const *)p, (char const *)q);
}
int
search(char const **p, char const *q, size_t nmemb, size_t size)
{
return bsearch(q, p, nmemb, size, cmp);
}
void
sort(char const **p, size_t nmemb, size_t size)
{
qsort(p, nmemb, size, cmp);
}