string的find用法
时间: 2023-09-08 20:12:26 浏览: 40
`find()`是string类中的一个成员函数,用于在字符串中查找子字符串并返回其位置。它的语法如下:
```
size_t find (const string& str, size_t pos = 0) const;
```
其中,`str`是要查找的子字符串,`pos`是要从哪个位置开始查找,默认为0。
`find()`函数会返回一个`size_t`类型的值,表示查找到的子字符串的位置。如果没有找到,则返回`string::npos`。
下面是一个示例:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "hello world";
std::string sub_str = "world";
size_t pos = str.find(sub_str);
if (pos != std::string::npos) {
std::cout << "Found at position " << pos << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
```
输出:
```
Found at position 6
```
在上面的例子中,`find()`函数查找字符串`"world"`在字符串`"hello world"`中的位置,并返回6,表示在字符串中的第7个位置找到了子字符串。