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;参数说明:
返回值:
立即学习“C++免费学习笔记(深入)”;
以下代码演示如何使用 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 << "Found '" << pattern << "' at position: " << pos << endl;
} else {
cout << "Not found" << endl;
}
return 0;
}
输出:
Found 'world' at position: 6可以设置起始查找位置,用于查找多个匹配项:
size_t pos = 0;这段代码会找出所有字符 'o' 的位置。
除了 find,string 还提供几个类似函数:
例如:
string s = "apple,banana,cherry";基本上就这些。使用 find 时注意检查返回值是否为 npos,避免误用无效下标访问字符串。
以上就是C++ string查找子串_C++ string find函数用法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号