字符串操作函数strstr
时间: 2023-07-21 14:06:02 浏览: 53
字符串操作函数strstr是C语言中的一个函数,用于在一个字符串中查找另一个字符串的第一次出现位置。它的原型如下:
```c
char* strstr(const char* haystack, const char* needle);
```
该函数接受两个参数,分别是待搜索的字符串haystack和要查找的字符串needle。它会在haystack中查找needle的第一次出现位置,并返回一个指向该位置的指针。如果找不到needle,则返回NULL。
下面是一个示例代码,演示了如何使用strstr函数:
```c
#include <stdio.h>
#include <string.h>
int main() {
const char* haystack = "Hello, world!";
const char* needle = "world";
char* result = strstr(haystack, needle);
if (result != NULL) {
printf("Found at index: %ld\n", result - haystack);
} else {
printf("Not found\n");
}
return 0;
}
```
输出结果为:
```
Found at index: 7
```
这表示在字符串"Hello, world!"中,子字符串"world"第一次出现在索引位置7处。
请注意,strstr函数是区分大小写的,如果需要不区分大小写的搜索,可以使用其他字符串操作函数来实现。