cstring find
时间: 2023-09-21 15:11:13 浏览: 62
C++的`std::string`类提供了多种方法来查找子字符串。其中最常用的方法是`find()`函数。`find()`函数可以用于查找一个子字符串在另一个字符串中的位置。
使用`find()`函数的基本语法如下:
```cpp
size_t find(const string& str, size_t pos = 0) const noexcept;
```
其中,`str`是要查找的子字符串,`pos`是起始查找位置,默认为0。
`find()`函数返回子字符串在原字符串中的位置,如果找到了子字符串,则返回第一次出现的位置;如果找不到,则返回`string::npos`。
以下是一个示例代码,演示了如何使用`find()`函数来查找子字符串:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string subStr = "World";
size_t position = str.find(subStr); // 查找子字符串
if (position != std::string::npos) {
std::cout << "子字符串在位置 " << position << " 找到了。" << std::endl;
} else {
std::cout << "子字符串未找到。" << std::endl;
}
return 0;
}
```
输出结果为:
```
子字符串在位置 7 找到了。
```
通过使用`find()`函数,我们可以轻松地在C++中查找子字符串并获取其位置。