strstr, strcasestr - locate a substring
定位子串
所需头文件
#include <string.h>
char *strstr(const char *haystack, const char *needle);
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <string.h>
char *strcasestr(const char *haystack, const char *needle);
The strstr() function finds the first occurrence of the substring needle in the string haystack. The terminating null bytes ('\0') are not compared.
The strcasestr() function is like strstr(), but ignores the case of both arguments.
strstr函数在haystack字符串里面查找跟needle字符串相等的子串,字符串结束符\0不参与比较
strcasestr函数跟strstr类似,但是忽略大小写
These functions return a pointer to the beginning of the substring, or NULL if the substring is not found.
这些函数返回匹配字串的开始处,如果没有找到匹配的子串则返回NULL
The strstr() function conforms to C89 and C99. The strcasestr() function is a nonstandard extension.
strstr函数遵从C89和C99标准,strcasestr函数不是一个标准的实现
Early versions of Linux libc (like 4.5.26) would not allow an empty needle argument for strstr(). Later versions (like 4.6.27) work correctly, and return haystack when needle is empty.
运行结果如下:
定位子串
所需头文件
#include <string.h>
char *strstr(const char *haystack, const char *needle);
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <string.h>
char *strcasestr(const char *haystack, const char *needle);
The strstr() function finds the first occurrence of the substring needle in the string haystack. The terminating null bytes ('\0') are not compared.
The strcasestr() function is like strstr(), but ignores the case of both arguments.
strstr函数在haystack字符串里面查找跟needle字符串相等的子串,字符串结束符\0不参与比较
strcasestr函数跟strstr类似,但是忽略大小写
These functions return a pointer to the beginning of the substring, or NULL if the substring is not found.
这些函数返回匹配字串的开始处,如果没有找到匹配的子串则返回NULL
The strstr() function conforms to C89 and C99. The strcasestr() function is a nonstandard extension.
strstr函数遵从C89和C99标准,strcasestr函数不是一个标准的实现
Early versions of Linux libc (like 4.5.26) would not allow an empty needle argument for strstr(). Later versions (like 4.6.27) work correctly, and return haystack when needle is empty.
早期linux libc(例如4.5.26)不允许needle参数是NULL,后续的版本(例如4.6.27)已经ok,当needle是NULL的时候返回haystack
testcase如下:
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *src = "abcdefg";
const char *needle1 = "cd";
const char *needle2 = "dE";
char *tmp = NULL;
tmp = strstr(src, needle1);
printf("tmp = %s\n", tmp);
tmp = strcasestr(src ,needle2);
printf("tmp = %s\n", tmp);
return 0;
}
运行结果如下:
cheny.le@cheny-ThinkPad-T420:~/cheny/testCode$ ./a.out
tmp = cdefg
tmp = defg