Find_last_of
时间: 2023-07-29 21:09:03 浏览: 48
`find_last_of` 是一个字符串成员函数,可以在字符串中搜索给定字符集中的任何一个字符,并返回最后一个匹配字符的位置。如果未找到匹配字符,则返回 `std::string::npos`。
以下是示例代码:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "Hello world!";
char ch = 'o';
size_t pos = str.find_last_of(ch);
if (pos != std::string::npos) {
std::cout << "The last position of '" << ch << "' in \"" << str << "\" is " << pos << std::endl;
} else {
std::cout << "No match found for '" << ch << "' in \"" << str << "\"" << std::endl;
}
return 0;
}
```
输出:
```
The last position of 'o' in "Hello world!" is 7
```
相关问题
find_last_of
find_last_of是C++中string类的一个成员函数,用于查找字符串中最后一个匹配某个字符的位置。它的语法为string.find_last_of(char c, size_t pos),其中c是要查找的字符,pos是从哪个位置开始查找。如果找到了匹配的字符,则返回该字符在字符串中的位置,否则返回string::npos。需要注意的是,find_last_of只能查找单个字符,不能查找字符串。
find_last_of详解
`find_last_of` 是 C++ 语言中 `string` 类的一个成员函数,用于在字符串中查找指定字符集合中的最后一个字符,并返回其下标(位置)。
函数原型如下:
```cpp
size_t find_last_of(const char* str, size_t pos = npos) const;
```
其中,`str` 表示指定的字符集合,`pos` 表示从哪个位置开始向前搜索,`npos` 表示搜索整个字符串。
函数返回指定字符集合中最后一个出现的字符的下标(位置),如果找不到,则返回 `string::npos`。
例如,对于字符串 `"hello world"`,调用该函数并指定字符集合为 `"ld"`,则返回值为 9,表示在字符串的倒数第二个字符 `"l"` 中找到了一个指定字符集合中的字符,其下标为 9。
需要注意的是,`find_last_of` 函数是从后往前搜索,如果想要从前往后搜索,则可以使用 `find_first_of` 函数。