C語言(函數)學習之strstr strcasestr

1、strstr函數使用

[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函數中參數嚴格"區分大小寫"字符串

2、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 *);
... ...         // 這種方法也能消除編譯時的警告信息
相關文章
相關標籤/搜索