strstr()
函数用于在一个字符串中查找子字符串的第一次出现,并返回子字符串在字符串中的起始位置。它的函数原型如下:
char *strstr(const char *haystack, const char *needle);
参数说明:
haystack
:指向要进行搜索的字符串。needle
:指向要搜索的子字符串。
返回值:
- 如果子字符串在字符串中找到,则返回指向子字符串第一次出现的位置(在
haystack
中的地址)。 - 如果子字符串不存在或者任一输入值为
NULL
,则返回NULL
。
例:
#include <stdio.h>
#include <string.h>
int main() {
const char *haystack = "Hello, World!";
const char *needle = "World";
const char *result = strstr(haystack, needle);//这里也应该是const char*
if (result != NULL) {
printf("子字符串 '%s' 找到在位置:%ld\n", needle, result - haystack);
} else {
printf("子字符串 '%s' 未找到\n", needle);
}
return 0;
}
输出结果:
子字符串 'World' 找到在位置:7
在上面的示例中,haystack
是要进行搜索的字符串,needle
是要搜索的子字符串。strstr(haystack, needle)
会搜索 haystack
中是否包含子字符串 needle
,如果找到,则返回指向第一次出现的位置的指针。注意,指针相减的结果表示子字符串在字符串中的起始位置。