C语言 strchr和strstr
时间: 2024-05-15 14:10:18 浏览: 24
strchr和strstr都是C语言中的字符串操作函数。
strchr函数用于在一个字符串中查找某个字符第一次出现的位置,其函数原型为:
```c
char *strchr(const char *str, int c);
```
其中,str为要查找的字符串,c为要查找的字符。如果在str中找到c,则返回c在str中第一次出现的地址;如果没有找到,则返回NULL。
例如,下面的代码用strchr函数查找字符串中是否含有某个字符:
```c
char str[] = "hello world";
char *ptr = strchr(str, 'w');
if(ptr != NULL) {
printf("找到了w在字符串中第一次出现的位置:%s\n", ptr);
} else {
printf("字符串中没有找到w\n");
}
```
strstr函数用于在一个字符串中查找另一个字符串第一次出现的位置,其函数原型为:
```c
char *strstr(const char *haystack, const char *needle);
```
其中,haystack为要查找的字符串,needle为要查找的子字符串。如果在haystack中找到了needle,则返回needle在haystack中第一次出现的地址;如果没有找到,则返回NULL。
例如,下面的代码用strstr函数查找字符串中是否含有另一个字符串:
```c
char str[] = "hello world";
char *ptr = strstr(str, "world");
if(ptr != NULL) {
printf("找到了world在字符串中第一次出现的位置:%s\n", ptr);
} else {
printf("字符串中没有找到world\n");
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c](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)