字串模糊查詢,主要是輸入不完全的資訊進行查詢,即每次查詢的是待查詢的內容中是否含有輸入的內容,如果有,則表示找到了。下面詳細的介紹下模糊查詢的實現方法,一起看看吧!
程式碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char * argv[])
{
char str[] = "hello welcome to china"; //源字串
printf("input a string:n");
char str2[20]; //要查詢的`字串
fgets(str2, 19, stdin);
char *res;
res = memchr(str, str2[0], strlen(str)); //根據要查詢的字串第一個字元,切割源字串
if (res == NULL)
{
printf("find nothing...n");
return 0;
}
int n;
while (1)
{
n = memcmp(res, str2, strlen(str2) - 1); //比較
if (n != 0)
{
if (strlen(res) <= strlen(str2)) //切割出的字串小於要查詢字串的長度
{
printf("find nothing...n");
return 0;
}
else
{
//根據要查詢的第一個字元繼續切割
res = memchr(res + 1, str2[0], strlen(res));
if (res == NULL)
{
printf("find nothing...n");
return 0;
}
}
}
else
{ //如果n = 0,找到
printf("%s is found..n", str2);
return 0;
}
}
}