zoukankan      html  css  js  c++  java
  • C语言(函数)学习之strstr strcasestr

    一、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!
    ");
        else printf("%s
    ", res);    // print:-->'host: www.baidu.com'
        res = strstr("xxxhost: www.baidu.com", "cookie");
        if(res == NULL) printf("res2 is NULL!
    ");
        else printf("%s
    ", 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!
    ");
        else printf("%s
    ", 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(i,j)=A(m,n,w)+B(m,n)
    误差处理相关
    http://blog.sina.com.cn/s/blog_4aae007d0100inxi.html
    全局变量和局部变量
    Yeelink:将复杂的传感器以极简的方式组到同一个网络内
    基站分布:GDOP
    C++学习路线图
    Matlab中三点确定质心
  • 原文地址:https://www.cnblogs.com/chenliyang/p/6633742.html
Copyright © 2011-2022 走看看