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

     

  • 相关阅读:
    多组件共享-vuex
    在子组件中触发事件,传值给父组件-vue
    在父组件中,直接获取子组件数据-vue
    非父子组件通过事件传值-vue
    在父组件中,传值给子组件-vue
    MVVM
    Virtual DOM-渲染函数render -vue
    duilib入门简明教程 -- VS环境配置(2) (转)
    duilib入门简明教程 -- 前言(1) (转)
    【CDockablePane】关于CDockablePane
  • 原文地址:https://www.cnblogs.com/liwei0526vip/p/4873109.html
Copyright © 2011-2022 走看看