strstr函数解释
时间: 2023-08-26 21:06:02 浏览: 51
strstr函数是C语言中的一个字符串处理函数,用于在一个字符串中查找另一个字符串的第一次出现位置。函数原型如下:
```c
char *strstr(const char *haystack, const char *needle);
```
函数参数:
- `haystack`:要搜索的字符串,也称为被搜索字符串或主串。
- `needle`:要查找的字符串,也称为模式串。
函数返回值:
- 如果找到了模式串在主串中的第一次出现位置,则返回指向该位置的指针。
- 如果没有找到匹配的位置,则返回NULL指针。
例如,下面的示例代码使用strstr函数查找字符串"Hello, World!"中是否包含子串"World":
```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 position: %ld\n", result - haystack);
} else {
printf("Not found\n");
}
return 0;
}
```
输出结果为:
```
Found at position: 7
```
这表示在主串中找到了模式串,并且它的起始位置在索引7处。