strrchr是什么函数
时间: 2023-12-24 13:56:03 浏览: 41
`strrchr()` 是一个标准库函数,用于在一个字符串中查找指定字符的最后一个出现位置。它的原型如下:
```c
char *strrchr(const char *str, int ch);
```
函数返回一个指向最后一个出现指定字符的指针,如果在字符串中没有找到指定的字符,则返回 NULL。该函数在头文件`<string.h>`中声明。
以下是一个例子,展示了如何使用 `strrchr()` 函数查找字符串中最后一个出现的字符:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
char *ptr = strrchr(str, 'o');
if (ptr != NULL) {
printf("Found last occurrence of 'o' at position %ld.\n", ptr - str);
} else {
printf("Didn't find 'o'.\n");
}
return 0;
}
```
输出结果为:
```
Found last occurrence of 'o' at position 8.
```
相关问题
strrchr()函数
`strrchr()` 是一个在 C 语言中常用的字符串函数,它用于查找一个字符串中最后一个匹配某个特定字符的索引。如果找到了匹配的字符,它会返回一个指向该字符的指针;如果没有找到,它会返回 NULL。
函数的原型通常如下:
```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 *last_ptr = strrchr(str, 'l');
if (last_ptr != NULL) {
printf("Last occurrence of 'l' is at position: %ld\n", (long) last_ptr - (long) str);
} else {
printf("Character not found.\n");
}
return 0;
}
```
这个程序会输出 "Last occurrence of 'l' is at position: 7",因为 'l' 在字符串中的最后一个位置是第 7 个字符。
需要注意的是,`strrchr()` 函数在找到匹配的字符后会移动到该字符之后的所有字符,所以在返回的指针中使用的 `-` 操作符不会得到最后一个匹配字符后的下一个字符。如果你想找到最后一个匹配字符后的下一个字符,你应该使用 `strchr()` 或 `memrchr()` 函数。
strrchr()函数
`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()`函数返回的是指针,需要将指针转换为对应的下标位置。