在字符串str1中找出字符串str2第一次出现的位置。如果出现,则返回str2 在str 1中的首地址
时间: 2024-03-20 08:39:40 浏览: 21
好的,你可以使用以下的 C语言代码实现这个功能:
```c
#include <stdio.h>
#include <string.h>
char* findSubstring(char* str1, char* str2) {
char* p = strstr(str1, str2);
if (p != NULL) {
return p;
} else {
return NULL;
}
}
int main() {
char str1[] = "hello world";
char str2[] = "world";
char* p = findSubstring(str1, str2);
if (p != NULL) {
printf("'%s' is found in '%s' at position %ld.\n", str2, str1, p - str1);
} else {
printf("'%s' is not found in '%s'.\n", str2, str1);
}
return 0;
}
```
这个函数的作用是在字符串 `str1` 中查找字符串 `str2` 第一次出现的位置,如果找到了,则返回 `str2` 在 `str1` 中的首地址。如果没有找到,则返回 `NULL`。
在上面的示例中,函数 `findSubstring` 被调用来查找字符串 `"world"` 在字符串 `"hello world"` 中的位置。如果找到了,则输出 "'world' is found in 'hello world' at position 6.",其中位置从0开始计算。如果没有找到,则输出 "'world' is not found in 'hello world'."。
希望这个代码能够帮到你!
相关推荐
![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)
![](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)