strrchr()函数
时间: 2023-11-11 09:18:47 浏览: 37
`strrchr()`函数是C语言中的一个字符串函数,用于查找一个字符串中最后一次出现某个字符的位置。该函数的原型如下:
```c
char* strrchr(const char* str, int ch);
```
其中,`str`是要查找的字符串,`ch`是要查找的字符。函数返回值是一个指向最后一个匹配字符的指针,如果未找到匹配字符,则返回`NULL`。
例如,下面的代码演示了如何使用`strrchr()`函数查找字符串中最后一次出现某个字符的位置:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello, world!";
char* p = strrchr(str, 'l');
if (p != NULL) {
printf("最后一个'l'的位置:%ld\n", p - str);
} else {
printf("未找到'l'\n");
}
return 0;
}
```
输出结果为:
```
最后一个'l'的位置:10
```
注意,`strrchr()`函数返回的是指针,需要将指针转换为对应的下标位置。
相关问题
strrchr函数
strrchr函数是一个C语言标准库函数,用于在一个字符串中查找最后一次出现某个字符的位置。其函数原型为:
```
char *strrchr(const char *s, int c);
```
其中,`s`表示要查找的字符串,`c`表示要查找的字符。函数返回一个指向最后一个出现`c`字符的指针,如果没找到则返回空指针。
例如,对于字符串`"hello world"`,调用`strrchr(str, 'l')`会返回指向`'d'`的指针,因为它是字符串中最后一个出现的`'l'`字符。
strrchr函数用法
strrchr函数用于在字符串中搜索指定字符的最后一次出现位置,并返回该位置及其后面的所有字符。
函数原型如下:
```c
char *strrchr(const char *str, int c)
```
参数说明:
- `str`:要搜索的字符串
- `c`:要搜索的字符
函数返回值:
- 如果找到指定字符,则返回该字符的地址;如果未找到指定字符,则返回NULL。
示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello World";
char *ptr;
ptr = strrchr(str, 'o');
if (ptr != NULL) {
printf("Last occurrence of 'o' found at position: %ld\n", ptr - str);
printf("Remaining string: %s\n", ptr);
} else {
printf("Character not found\n");
}
return 0;
}
```
输出结果:
```
Last occurrence of 'o' found at position: 7
Remaining string: orld
```
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)