c++string的find函数
时间: 2025-04-17 16:42:07 浏览: 37
### C++ 中 `string` 类的 `find` 函数使用方法
#### 查找子串并获取其起始位置
当需要在一个字符串中查找特定子串时,可以使用 `find` 方法。此方法返回被查找到的第一个匹配项的位置索引;如果未找到,则返回 `string::npos`。
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World";
std::string target = "World";
std::string::size_type pos = str.find(target);
if (pos != std::string::npos) {
std::cout << "Found at position: " << pos << '\n';
} else {
std::cout << "Not Found\n";
}
return 0;
}
```
这段代码展示了如何通过调用 `str.find(target)` 来定位目标子串 `"World"` 在源字符串 `"Hello World"` 中首次出现的位置[^1]。
#### 设置查找起点
可以通过指定第二个参数来设定从哪个位置开始执行搜索操作。这允许程序跳过某些部分而只关注感兴趣的区域。
```cpp
std::string text = "programming is fun and games are also fun";
std::string word = "fun";
// 从第8个字符之后开始寻找单词 'fun'
std::string::size_type index = text.find(word, 8);
if(index != std::string::npos){
std::cout << "'fun' found after position 8 at : " << index << "\n";
} else{
std::cout << "'fun' not found after position 8.\n";
}
```
这里说明了如何利用额外的参数控制查找范围,从而提高效率或实现更复杂的逻辑需求[^4]。
#### 处理找不到的情况
对于未能成功匹配的情形,应该始终检查返回的结果是否等于 `string::npos`,这是标准库定义的一个常量,用来指示不存在有效结果的状态。
```cpp
#include <iostream>
#include <string>
using namespace std;
int main(){
string s1="Hello World Hello World";
size_t find_pos=s1.find("abc");
if(find_pos==string::npos){ // 注意这里是 == 而不是 =
cout<<"找不到";
}
else{
cout<<find_pos;
}
return 0;
}
```
上述例子修正了一个常见的错误——将赋值运算符 `=` 错误地用于条件判断语句中,并正确处理了无法找到模式串的情景[^3]。
阅读全文
相关推荐



















