string反向查找字符
时间: 2023-09-29 09:06:50 浏览: 55
可以使用Python中的rfind()函数进行字符串反向查找字符。
rfind()函数可以在字符串中从右往左查找指定字符,并返回其最后一次出现的位置。如果未找到该字符,则返回-1。
示例代码:
```python
s = "Hello World"
index = s.rfind("o")
print("最后一个'o'的位置为:", index)
```
输出:
```
最后一个'o'的位置为: 7
```
在上面的例子中,字符串s中最后一个字符'o'的位置为7。
相关问题
c++ string反向查找字符
要在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
```