码迷,mamicode.com
首页 > 编程语言 > 详细

C语言(函数)学习之strstr strcasestr

时间:2017-03-28 13:36:06      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:stdio.h   技术分享   define   copy   .com   com   成功   strstr函数   bsp   

一、strstr函数使用

[1] 函数原型

char *strstr(const char *haystack, const char *needle);

[2] 头文件

#include <string.h>

[3] 函数功能

搜索"子串"在"指定字符串"中第一次出现的位置

[4] 参数说明

haystack        -->被查找的目标字符串"父串"
needle          -->要查找的字符串对象"子串"

注:若needle为NULL, 则返回"父串"

[5] 返回值

(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] 特别说明

注:strstr函数中参数严格"区分大小写"

二、strcasestr函数

[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 *);
... ...         // 这种方法也能消除编译时的警告信息

C语言(函数)学习之strstr strcasestr

标签:stdio.h   技术分享   define   copy   .com   com   成功   strstr函数   bsp   

原文地址:http://www.cnblogs.com/chenliyang/p/6633742.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!