帮我写一下strstr函数
时间: 2023-07-07 16:45:52 浏览: 42
好的,以下是一个简单的 strstr 函数的实现:
```
char* my_strstr(const char* str1, const char* str2)
{
const char *p1, *p2, *p3;
if (!*str2) {
return (char *)str1;
}
for (p1 = str1; *p1; p1++) {
p2 = str2;
p3 = p1;
while (*p3 && *p2 && *p3 == *p2) {
p3++;
p2++;
}
if (!*p2) {
return (char *)p1;
}
}
return NULL;
}
```
该函数的作用是在字符串 str1 中查找第一次出现字符串 str2 的位置,并返回该位置的指针。如果未找到,则返回 NULL。
相关问题
解释一下strstr函数
`strstr` 函数是 C/C++ 标准库中的一个字符串处理函数,用于在一个字符串中查找另一个字符串第一次出现的位置。该函数的语法如下:
```c++
char* strstr(const char* str1, const char* str2);
```
其中,`str1` 是要查找的字符串,`str2` 是要查找的子字符串。该函数会在 `str1` 中查找第一个出现的 `str2`,并返回指向该位置的指针。如果 `str2` 不存在于 `str1` 中,则返回 `NULL`。
例如,要在字符串 `str` 中查找子字符串 `sub` 的位置,可以使用以下代码:
```c++
char str[] = "Hello, world!";
char sub[] = "wor";
char* result = strstr(str, sub);
```
上述代码会在字符串 `str` 中查找子字符串 `sub` 的位置,并将指向该位置的指针赋值给 `result`。
需要注意的是,`strstr` 函数只能查找第一次出现的位置,如果要查找所有出现的位置,则需要使用其他字符串处理函数来实现。
演示一下strstr函数
strstr函数是C语言中的字符串函数,用于在一个字符串中查找另一个子字符串的位置。下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello, world!";
char *ptr = strstr(str, "world");
if (ptr != NULL) {
printf("Substring found at position %d.\n", ptr - str);
} else {
printf("Substring not found.\n");
}
return 0;
}
```
以上代码会在字符串“hello, world!”中查找子字符串“world”,并输出其位置。如果找到了,则会输出“Substring found at position x.”,其中x是子字符串在原字符串中的起始位置。如果没有找到,则会输出“Substring not found.”。
输出结果为:
```
Substring found at position 7.
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)