在 C++ 的 std::string
类中,有几个成员函数可以用于在字符串中执行搜索和子字符串提取操作。以下是这些函数的简要说明:
-
find()
: 查找子字符串的第一个出现位置。size_t find(const string& str, size_t pos = 0) const; size_t find(const char* s, size_t pos = 0) const;
这个函数返回子字符串
str
或 C 字符串s
第一次出现的位置(索引)。可以指定搜索的起始位置pos
。如果找不到子字符串,返回string::npos
。 -
rfind()
: 反向查找子字符串的最后一个出现位置。size_t rfind(const string& str, size_t pos = npos) const; size_t rfind(const char* s, size_t pos = npos) const;
这个函数返回子字符串
str
或 C 字符串s
最后一次出现的位置(索引)。可以指定搜索的起始位置pos
,默认情况下从字符串的末尾开始搜索。如果找不到子字符串,返回string::npos
。 -
find_first_of()
: 查找给定字符集合中任意字符第一次出现的位置。size_t find_first_of(const string& str, size_t pos = 0) const; size_t find_first_of(const char* s, size_t pos = 0) const;
这个函数返回在子字符串
str
或 C 字符串s
中任意字符的第一次出现的位置(索引)。可以指定搜索的起始位置pos
。如果找不到字符,返回string::npos
。 -
find_last_of()
: 反向查找给定字符集合中任意字符最后一次出现的位置。size_t find_last_of(const string& str, size_t pos = npos) const; size_t find_last_of(const char* s, size_t pos = npos) const;
这个函数返回在子字符串
str
或 C 字符串s
中任意字符的最后一次出现的位置(索引)。可以指定搜索的起始位置pos
,默认情况下从字符串的末尾开始搜索。如果找不到字符,返回string::npos
。 -
substr()
: 提取子字符串。string substr(size_t pos = 0, size_t len = npos) const;
这个函数返回从位置
pos
开始,长度为len
的子字符串副本。如果省略len
,则返回从pos
开始的剩余部分。
具体示例:
#include <iostream>
#include <string>int main() {std::string str = "Hello, World!";// 使用 find() 查找子字符串的第一个出现位置size_t pos = str.find("World");if (pos != std::string::npos) {std::cout << "'World' found at position " << pos << std::endl;} else {std::cout << "'World' not found" << std::endl;}// 使用 rfind() 反向查找子字符串的最后一个出现位置size_t pos_reverse = str.rfind("o");if (pos_reverse != std::string::npos) {std::cout << "'o' found at position " << pos_reverse << std::endl;} else {std::cout << "'o' not found" << std::endl;}// 使用 find_first_of() 查找给定字符集合中任意字符的第一个出现位置size_t pos_first_of = str.find_first_of("eio");if (pos_first_of != std::string::npos) {std::cout << "Any of 'eio' found at position " << pos_first_of << std::endl;} else {std::cout << "Any of 'eio' not found" << std::endl;}// 使用 find_last_of() 反向查找给定字符集合中任意字符的最后一个出现位置size_t pos_last_of = str.find_last_of("rlod");if (pos_last_of != std::string::npos) {std::cout << "Any of 'rlod' found at position " << pos_last_of << std::endl;} else {std::cout << "Any of 'rlod' not found" << std::endl;}// 使用 substr() 提取子字符串std::string substr = str.substr(7, 5);std::cout << "Substring: " << substr << std::endl;return 0;
}
输出结果:
'World' found at position 7
'o' found at position 8
Any of 'eio' found at position 1
Any of 'rlod' found at position 13
Substring: World
以上示例演示了如何使用这些函数在字符串中查找子字符串并提取子字符串的各种操作。