strstr函数示例
时间: 2024-06-26 16:01:05 浏览: 4
`strstr` 是 C 语言中的一个字符串搜索函数,用于在一个字符串中查找指定子串首次出现的位置。这个函数在 `<string.h>` 头文件中定义。函数原型如下:
```c
char *strstr(const char *haystack, const char *needle);
```
- `haystack`:要在其中查找子串的原始字符串(也称为“主串”)。
- `needle`:要在 `haystack` 中查找的子字符串。
如果找到了匹配的子串,`strstr` 函数返回指向子串的第一个字符的指针;如果没有找到,函数会返回 `NULL`。
这里有一个简单的示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char substr[] = "World";
if (strstr(str, substr)) {
printf("Substring found at position %ld\n", (long)strstr(str, substr) - str);
} else {
printf("Substring not found.\n");
}
return 0;
}
```
在这个例子中,`strstr(str, substr)` 会返回 `str + 7`,因为 "World" 在 "Hello, World!" 中的位置是第8个字符开始,所以位置是 `7`(从0开始计数)。如果子串不存在,`strstr` 将返回 `NULL`,然后程序会打印 "Substring not found."。