阅读量:92
在C++中,str.find()函数用于在字符串中查找特定子串的位置。其参数包括要查找的子串以及可选的起始位置。
语法如下:
size_t find (const string& str, size_t pos = 0) const noexcept;
其中,参数的含义如下:
- str: 要查找的子串
- pos: 查找的起始位置,默认为0
使用示例:
#include
#include
int main() {
std::string str = "Hello, World!";
std::string sub = "World";
// 在字符串中查找子串的位置
size_t found = str.find(sub);
if (found != std::string::npos) {
std::cout << "子串在字符串中的位置为:" << found class="hljs-keyword">else {
std::cout << "子串未找到" << std class="hljs-keyword">return 0;
}
在上面的示例中,我们使用find()方法在字符串中查找子串"World"的位置,并输出结果。如果子串存在,则返回子串在字符串中的起始位置,否则返回std::string::npos。