C语言之字符串模糊查询方法的实现

2020-01-06 13:20:34于海丽

本篇文章主要为大家介绍字符串模糊查询的C语言程序编写方法,有需要的朋友可以参考下

字符串模糊查询,主要是输入不完全的信息进行查找,即每次查找的是待查询的内容中是否含有输入的内容,如果有,则表示找到了。下面详细的介绍下模糊查询的实现方法,代码如下:

 

 
  1. #include <stdio.h>  #include <stdlib.h> 
  2. #include <string.h>   
  3. int main(int argc, const char * argv[])  { 
  4. char str[] = "hello welcome to china"; //源字符串  printf("input a string:n");  
  5. char str2[20]; //要查找的字符串  fgets(str2, 19, stdin); 
  6. char *res;  res = memchr(str, str2[0], strlen(str)); //根据要查找的字符串第一个字符,切割源字符串 
  7. if (res == NULL)  { 
  8. printf("find nothing...n");  return 0; 
  9. }   
  10. int n;  while (1) 
  11. {  n = memcmp(res, str2, strlen(str2) - 1); //比较 
  12. if (n != 0)  { 
  13. if (strlen(res) <= strlen(str2)) //切割出的字符串小于要查找字符串的长度  { 
  14. printf("find nothing...n");  return 0; 
  15. }  else 
  16. {   //根据要查找的第一个字符继续切割 
  17. res = memchr(res + 1, str2[0], strlen(res));   if (res == NULL) 
  18. {  printf("find nothing...n"); 
  19. return 0;  } 
  20.   } 
  21. }  else 
  22. { //如果n = 0,找到  printf("%s is found..n", str2); 
  23. return 0;  } 
  24. }  }