c++中string.find()
时间: 2023-12-07 10:46:04 浏览: 237
在C++中,`string.find()`是一个成员函数,用于在字符串中搜索指定的子字符串。它返回找到的子字符串的第一个出现位置的索引,如果未找到,则返回`string::npos`。
以下是`string.find()`的基本语法:
```cpp
size_t find (const string& str, size_t pos = 0) const;
```
- `str`是要搜索的子字符串。
- `pos`是搜索的起始位置,默认为0。
例如,假设有一个字符串`str = "Hello, World!"`,我们想要找到子字符串"World"的位置,可以使用`find()`函数:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
size_t found = str.find("World");
if (found != std::string::npos) {
std::cout << "Substring found at position: " << found << std::endl;
} else {
std::cout << "Substring not found." << std::endl;
}
return 0;
}
```
输出结果将是:
```
Substring found at position: 7
```
这表明子字符串"World"在位置7处被找到。如果子字符串未找到,输出将是"Substring not found."。
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)