C語言之字符串模糊查詢方法的實現

來源:文萃谷 1.74W

字符串模糊查詢,主要是輸入不完全的信息進行查找,即每次查找的是待查詢的內容中是否含有輸入的內容,如果有,則表示找到了。下面詳細的介紹下模糊查詢的實現方法,一起看看吧!

C語言之字符串模糊查詢方法的實現

  代碼如下:

#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;

}

}

}

熱門標籤