本篇文章主要为大家介绍字符串模糊查询的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; }
- } }










