c++ std::string find用法
时间: 2025-06-01 15:01:26 浏览: 27
### C++ 中 `std::string::find` 方法的使用指南
`std::string::find` 是 C++ 标准库中用于在字符串中查找子字符串或字符的方法。它提供了多种重载形式,可以满足不同的查找需求[^4]。
#### 函数原型
以下是 `std::string::find` 的主要函数原型:
```cpp
size_t find(const string& str, size_t pos = 0) const;
size_t find(const char* s, size_t pos = 0) const;
size_t find(char c, size_t pos = 0) const;
```
#### 参数说明
- `str`:要查找的子字符串。
- `s`:要查找的 C 风格字符串。
- `c`:要查找的单个字符。
- `pos`:开始查找的起始位置,默认为 0。
#### 返回值
如果找到目标字符串或字符,`std::string::find` 返回其第一次出现的位置(从 0 开始计数)。如果未找到,则返回 `std::string::npos`,这是一个特殊的常量,表示查找失败[^4]。
#### 示例代码
以下是一些常见的用法示例:
##### 查找子字符串
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
std::string sub = "world";
size_t found = str.find(sub);
if (found != std::string::npos) {
std::cout << "Substring found at position: " << found << std::endl;
} else {
std::cout << "Substring not found" << std::endl;
}
return 0;
}
```
##### 查找单个字符
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
char c = 'o';
size_t found = str.find(c);
if (found != std::string::npos) {
std::cout << "Character found at position: " << found << std::endl;
} else {
std::cout << "Character not found" << std::endl;
}
return 0;
}
```
##### 指定起始位置查找
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
char c = 'o';
size_t pos = 5;
size_t found = str.find(c, pos);
if (found != std::string::npos) {
std::cout << "Character found at position: " << found << std::endl;
} else {
std::cout << "Character not found after position " << pos << std::endl;
}
return 0;
}
```
#### 注意事项
1. 如果需要查找所有匹配项,可以通过循环调用 `find` 并更新起始位置来实现[^4]。
2. 使用 `std::string::npos` 判断查找结果时,需确保正确处理未找到的情况。
3. `std::string::find` 是区分大小写的。
阅读全文
相关推荐

















