c++ string反向查找字符
时间: 2023-09-02 07:14:12 浏览: 46
要在C字符串中反向查找字符,可以使用strrchr函数。该函数从字符串的末尾开始搜索,直到找到指定的字符,然后返回该字符的指针。如果未找到字符,则返回NULL。
以下是一个示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world";
char *ptr;
ptr = strrchr(str, 'l');
if (ptr != NULL) {
printf("Last occurrence of 'l' found at position: %ld\n", ptr - str);
} else {
printf("'l' not found in string.\n");
}
return 0;
}
```
输出:
```
Last occurrence of 'l' found at position: 9
```
相关问题
C++ std::string反向查找字符
使用std::string的rfind()函数可以反向查找字符,该函数从字符串的末尾开始查找,返回最后一次出现字符的位置。
例如,以下代码查找字符串中最后一次出现字符'c'的位置:
```
#include <iostream>
#include <string>
int main() {
std::string str = "abcdefgchijklmnc";
int pos = str.rfind('c');
std::cout << "Last position of 'c' is: " << pos << std::endl;
return 0;
}
```
输出结果为:
```
Last position of 'c' is: 14
```
c++反向输出字符串
要反向输出一个字符串,你可以使用循环遍历字符串并逐个打印字符,但是按相反的顺序。下面是一个示例代码:
```python
def reverse_string(input_str):
reversed_str = ""
for char in input_str[::-1]:
reversed_str += char
return reversed_str
input_str = "Hello, World!"
reversed_str = reverse_string(input_str)
print(reversed_str)
```
这段代码使用了切片操作符 `[::-1]` 来逆序遍历输入字符串,并将每个字符追加到新的字符串 `reversed_str` 中。最后,打印出反向输出的字符串。
运行上述代码,输出将会是:`!dlroW ,olleH`,即输入字符串 "Hello, World!" 的反向输出。