string.rfind
时间: 2024-06-15 22:07:40 浏览: 8
string.rfind是一个字符串方法,用于在字符串中从右向左查找指定子字符串的位置。它返回最后一次出现该子字符串的索引,如果未找到则返回-1。
该方法的语法如下:
```python
string.rfind(sub, start, end)
```
其中,sub是要查找的子字符串;start和end是可选参数,用于指定查找的起始和结束位置。
如果只提供了sub参数,则从整个字符串的末尾开始查找;如果同时提供了start参数,则从指定位置开始向左查找;如果同时提供了end参数,则在指定位置之前停止查找。
下面是一个示例:
```python
sentence = "I have a cat, a dog, and a rabbit."
index = sentence.rfind("a")
print(index) # 输出:26
```
相关问题
c++ string.rfind
`string.rfind()` 是 C++ 标准库中的一个成员函数,用于在字符串中从后往前查找指定字符或子字符串第一次出现的位置。该函数的定义如下:
```cpp
size_t rfind(const string& str, size_t pos = npos) const;
size_t rfind(const char* s, size_t pos = npos) const;
size_t rfind(const char* s, size_t pos, size_t n) const;
size_t rfind(char c, size_t pos = npos) const;
```
其中,第一个参数可以是 `string` 对象或者 `const char*` 类型的字符串,表示要查找的子字符串;第二个参数是可选的,表示查找的起始位置,默认为字符串的末尾。
该函数会返回一个 `size_t` 类型的整数,表示子字符串在原字符串中的位置。如果没有找到,则返回 `string::npos`。
例如,下面的代码演示了使用 `rfind()` 函数查找字符串中最后一个空格的位置:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World, Welcome to C++!";
size_t pos = str.rfind(' ');
std::cout << "The last space is at position " << pos << std::endl;
return 0;
}
```
输出结果为:
```
The last space is at position 26
```
wstring.rfind()
`rfind`函数是`wstring`类的成员函数,用于在字符串中从后往前查找指定的子串并返回其位置。其用法与`find`函数类似,只是查找方向相反。示例如下:
```c++
#include <iostream>
#include <string>
int main() {
std::wstring str = L"这是一个测试测试字符串";
std::wstring substr = L"测试";
size_t pos = str.rfind(substr); // 从后往前查找子串的位置
if (pos != std::wstring::npos) { // 如果找到了子串
std::wcout << L"子串在字符串中的位置:" << pos << std::endl; // 输出:子串在字符串中的位置:9
} else { // 如果没有找到子串
std::wcout << L"字符串中没有找到子串" << std::endl;
}
return 0;
}
```
需要注意的是,`rfind`函数返回的位置是从0开始计数的,如果没有找到子串,则返回`std::wstring::npos`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)