在C语言中,strstr()函数是一个字符串处理函数,它用于在一个字符串中查找另一个字符串的出现位置。函数原型为:
char *strstr(const char *str1, const char *str2);
该函数接受两个参数,都是指向字符串的指针。第一个参数 str1 表示待查找的字符串,第二个参数 str2 表示要查找的子字符串。
函数返回一个指向字符串中第一次出现 str2 子字符串的位置的指针。如果没有找到,该函数返回 NULL。
下面是一个简单的示例代码,演示了如何使用 strstr() 函数:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello world";
char str2[] = "world";
char *result = strstr(str1, str2);
if (result != NULL) {
printf("'%s' was found in '%s'\n", str2, str1);
printf("'%s' starts at index %ld\n", result, result - str1);
} else {
printf("'%s' was not found in '%s'\n", str2, str1);
}
return 0;
}
该程序输出:
'world' was found in 'hello world'
'world' starts at index 6
上面的程序中,我们使用了 strstr() 函数查找字符串 “world” 是否出现在字符串 “hello world” 中,并打印出了其在字符串中的位置。注意,我们可以通过计算返回指针和字符串首地址之间的差值来获取它在字符串中的索引位置。