strstr函数头文件_C语言(函数)学习之strstr strcasestr
一、strstr函數使用
[1]?函數原型
char *strstr(const char *haystack, const char *needle);
[2]?頭文件
#include
[3]?函數功能
搜索"子串"在"指定字符串"中第一次出現的位置
[4]?參數說明
haystack -->被查找的目標字符串"父串"
needle -->要查找的字符串對象"子串"
注:若needle為NULL,?則返回"父串"
[5]?返回值
(1) 成功找到,返回在"父串"中第一次出現的位置的 char *指針
(2) 若未找到,也即不存在這樣的子串,返回: "NULL"
[6]?程序舉例
#include
#include
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
char *strcasestr(const char *haystack, const char *needle);
[4]?程序舉例
#define _GNU_SOURCE // 宏定義必須有,否則編譯會有Warning警告信息
#include
#include
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
... ...
extern char *strcasestr(const char *, const char *);
... ... // 這種方法也能消除編譯時的警告信息
總結
以上是生活随笔為你收集整理的strstr函数头文件_C语言(函数)学习之strstr strcasestr的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言个人通讯录管理系统实验报告_C语言
- 下一篇: 你们看帖子会自动跳到搜狗网址导航吗?