在C语言中,strstr()是一个字符串函数,用于查找一个字符串中是否包含另一个字符串,并返回第一次出现该子字符串的位置。其函数原型为:
char *strstr(const char *haystack, const char *needle);
其中,haystack参数表示要查找的字符串,needle参数表示要查找的子字符串。函数返回指向第一次出现needle的位置的指针,如果没有找到,返回NULL。
下面是一个使用strstr()函数查找子字符串的例子:
#include <stdio.h>
#include <string.h>
int main()
{ char str1[] = "Hello, world!";
char str2[] = "world";
char *result;
result = strstr(str1, str2);
if (result == NULL)
{
printf("'%s' not found in '%s'\n", str2, str1);
}
else
{
printf("'%s' found in '%s' at position %ld\n", str2, str1, result - str1);
}
return 0;
}
输出结果为:
'world' found in 'Hello, world!' at position 7
上述例子中,我们首先定义了两个字符串str1和str2,然后调用strstr()函数查找str2在str1中的位置,最后输出结果。需要注意的是,strstr()函数是区分大小写的,如果要不区分大小写,可以使用strcasestr()函数。