std::string的find函数用于查找子串或字符,找到返回下标,否则返回npos;可指定起始位置进行多次查找;还提供rfind、find_first_of等变体函数实现不同查找需求。
在C++中,std::string 提供了 find() 成员函数,用于查找子串或字符在字符串中的位置。如果找到,返回首次出现的下标;如果未找到,返回 std::string::npos。
函数原型如下:
size_t find(const string& str, size_t pos = 0) const;参数说明:
返回值:
以下代码演示如何使用 find 查找子串:
#include iostream>int main() {
string text = "Hello world, welcome to C++ programming";
string pattern = "world";
size_t pos = text.find(pattern);
if (pos != string::npos) {
cout
} else {
cout
}
ret
urn 0;
}
输出:
Found 'world' at position: 6可以设置起始查找位置,用于查找多个匹配项:
size_t pos = 0;这段代码会找出所有字符 'o' 的位置。
除了 find,string 还提供几个类似函数:
例如:
string s = "apple,banana,cherry";基本上就这些。使用 find 时注意检查返回值是否为 npos,避免误用无效下标访问字符串。