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!\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 *);
... ...         // 這種方法也能消除編譯時的警告信息


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM