[1] 函数原型编程
char *strstr(const char *haystack, const char *needle);
[2] 头文件cookie
#include <string.h>
[3] 函数功能函数
搜索"子串"在"指定字符串"中第一次出现的位置
[4] 参数说明spa
haystack -->被查找的目标字符串"父串" needle -->要查找的字符串对象"子串"
注:若needle为NULL, 则返回"父串"指针
[5] 返回值code
(1) 成功找到,返回在"父串"中第一次出现的位置的 char *指针 (2) 若未找到,也即不存在这样的子串,返回: "NULL"
[6] 程序举例对象
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char *res = strstr("xxxhost: www.baidu.com", "host"); if(res == NULL) printf("res1 is NULL!\n"); else printf("%s\n", res); // print:-->'host: www.baidu.com' res = strstr("xxxhost: www.baidu.com", "cookie"); if(res == NULL) printf("res2 is NULL!\n"); else printf("%s\n", res); // print:-->'res2 is NULL!' return 0; }
[7] 特别说明blog
注:strstr函数中参数严格"区分大小写"字符串
[1] 描述原型
strcasestr函数的功能、使用方法与strstr基本一致。
[2] 区别
strcasestr函数在"子串"与"父串"进行比较的时候,"不区分大小写"
[3] 函数原型
#define _GNU_SOURCE #include <string.h> char *strcasestr(const char *haystack, const char *needle);
[4] 程序举例
#define _GNU_SOURCE // 宏定义必须有,不然编译会有Warning警告信息 #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char *res = strstr("xxxhost: www.baidu.com", "Host"); if(res == NULL) printf("res1 is NULL!\n"); else printf("%s\n", res); // print:-->'host: www.baidu.com' return 0; }
[5] 重要细节
若是在编程时没有定义"_GNU_SOURCE"宏,则编译的时候会有警告信息
warning: initialization makes pointer from integer without a cast
缘由:
strcasestr函数并不是是标准C库函数,是扩展函数。函数在调用以前未经声明的默认返回int型
解决:
要在#include全部头文件以前加 #define _GNU_SOURCE
另外一种解决方法:(可是不推荐)
在定义头文件下方,本身手动添加strcasestr函数的原型声明
#include <stdio.h> ... ... extern char *strcasestr(const char *, const char *); ... ... // 这种方法也能消除编译时的警告信息