C++的strstr怎么使用
时间: 2024-05-17 21:14:11 浏览: 19
C语言的strstr函数用于在一个字符串中查找子字符串的第一次出现位置。它的函数原型如下:
```c
char *strstr(const char *haystack, const char *needle);
```
其中,haystack是要查找的字符串,needle是要搜索的子字符串。该函数会返回一个指向子字符串在主字符串中第一次出现位置的指针,如果子字符串不存在,则返回NULL。
下面是一个使用strstr函数的示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "Hello, World!";
const char *subStr = "World";
char *result = strstr(str, subStr);
if (result != NULL) {
printf("子字符串在主字符串中的位置: %ld\n", result - str);
} else {
printf("子字符串不存在\n");
}
return 0;
}
```
在上面的代码中,我们定义了一个主字符串str和一个要搜索的子字符串subStr。然后使用strstr函数在主字符串中查找子字符串,并将返回的指针赋值给result变量。最后,通过判断result是否为NULL来确定子字符串是否存在,并打印出子字符串在主字符串中的位置。
注意:如果子字符串重复出现在主字符串中,strstr函数只会返回第一次出现位置的指针。如果需要查找所有出现位置,可以使用循环结合指针偏移来实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)