std::string s = "hello, world!"; size_t pos = s.find_last_of("ow");
时间: 2024-04-01 16:37:11 浏览: 14
在这个例子中,`s` 是一个字符串,值为 `"hello, world!"`。`pos` 是一个 `size_t` 类型的变量,用于存储查找结果。
`find_last_of()` 函数查找字符串 `s` 中最后一个出现在字符集合 `"ow"` 中的字符,并返回其位置。
在这个例子中,字符集合 `"ow"` 包含字符 `'o'` 和 `'w'`。因此,函数将从字符串 `s` 的末尾开始向前查找,在位置 11 找到字符 `'o'`,并将其位置返回给变量 `pos`。
因此,执行完这段代码后,变量 `pos` 的值为 11。
相关问题
find_first_of和find_last_of及相关函数并举例
除了 `find_first_of`,`std::string` 类中还有一些其他的查找函数,它们的作用都是在字符串中查找指定字符或字符集的位置。下面是几个常用的查找函数及其功能:
1. `find(char ch, size_t pos = 0) const`:在字符串中查找字符 `ch` 的位置,从 `pos` 位置开始查找,默认值为 0。
```cpp
std::string s = "hello, world!";
size_t pos = s.find('o'); // 返回 4
```
2. `rfind(char ch, size_t pos = npos) const`:在字符串中查找字符 `ch` 的位置,从 `pos` 位置往前查找,`npos` 表示从字符串的末尾开始查找。
```cpp
std::string s = "hello, world!";
size_t pos = s.rfind('o'); // 返回 8
```
3. `find_first_of(const char* str, size_t pos = 0) const`:在字符串中查找第一个匹配指定字符集中任意一个字符的位置。
```cpp
std::string s = "hello, world!";
size_t pos = s.find_first_of("ow"); // 返回 4
```
4. `find_last_of(const char* str, size_t pos = npos) const`:在字符串中查找最后一个匹配指定字符集中任意一个字符的位置。
```cpp
std::string s = "hello, world!";
size_t pos = s.find_last_of("ow"); // 返回 9
```
5. `find_first_not_of(const char* str, size_t pos = 0) const`:在字符串中查找第一个不匹配指定字符集中任意一个字符的位置。
```cpp
std::string s = "hello, world!";
size_t pos = s.find_first_not_of("helo, "); // 返回 5
```
6. `find_last_not_of(const char* str, size_t pos = npos) const`:在字符串中查找最后一个不匹配指定字符集中任意一个字符的位置。
```cpp
std::string s = "hello, world!";
size_t pos = s.find_last_not_of("dlrow!"); // 返回 10
```
find_first_of
`find_first_of` 是 C++ 中 `std::string` 类的成员函数之一,用于在字符串中查找第一个匹配指定字符集中任意一个字符的位置。
该函数有两个重载版本:
1. `size_t find_first_of(const char* str, size_t pos = 0) const;`
2. `size_t find_first_of(const string& str, size_t pos = 0) const;`
第一个版本接受一个 C 风格字符串 `str` 作为参数,第二个版本接受一个 `std::string` 对象 `str` 作为参数,两个版本的第二个参数 `pos` 都是可选的,表示从字符串的哪个位置开始查找,默认值为 0。
这个函数会在字符串中从 `pos` 位置开始往后查找,找到第一个匹配指定字符集中任意一个字符的位置并返回该位置。如果字符串中没有匹配的字符,则返回 `string::npos`。
例如,对于字符串 `"hello, world!"`,调用 `find_first_of("ow")` 会返回 4,表示该字符串中第一个匹配字符集 `"ow"` 中任意一个字符的位置是在第 4 个字符处,也就是字符 `'o'`。