c++ string之rfind

本文详细介绍了C++标准库中string类的find()方法及其变种rfind()的使用方法。find()方法包括查找string对象、查找字符串、查找字符串的前n个字符以及查找单个字符等四种形式,并阐述了每种情况下的返回结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

string中 find()的应用  (rfind() 类似,只是从反向查找
原型如下:
(1)size_t find (const string& str, size_t pos = 0) const;  //查找对象--string类对象
(2)size_t find (const char* s, size_t pos = 0) const; //查找对象--字符串
(3)size_t find (const char* s, size_t pos, size_t n) const;  //查找对象--字符串的前n个字符
(4)size_t find (char c, size_t pos = 0) const;  //查找对象--字符
结果:找到 -- 返回 第一个字符的索引
     没找到--返回   string::npos
### C++ `string::find` 函数的用法 在C++标准库中,`std::string` 提供了一个成员函数 `find` 来定位子字符串的位置。如果找到匹配项,则返回该位置;如果没有找到,则返回 `std::string::npos`。 #### 基础语法 ```cpp size_t find(const string& str, size_t pos = 0) const noexcept; ``` - 参数 `str`: 要查找的子串。 - 参数 `pos`: 开始查找的位置,默认为0表示从头开始[^1]。 #### 实际应用案例 下面是一个完整的代码示例展示如何使用 `string::find` 方法: ```cpp #include <iostream> #include <string> int main() { std::string s = "hello world"; // 查找单个字符 'o' size_t index_char = s.find('o'); if (index_char != std::string::npos) std::cout << "'o' first occurs at position: " << index_char << '\n'; // 查找整个单词 "world" size_t index_word = s.find("world"); if (index_word != std::string::npos) std::cout << "\"world\" starts from position: " << index_word << '\n'; // 尝试在一个不存在的情况下寻找 size_t missing_index = s.find("universe"); if (missing_index == std::string::npos) std::cout << "The word \"universe\" is not present.\n"; return 0; } ``` 这段程序展示了三种情况下的查找操作:成功查找到了单个字符、成功查到了一个词组以及未能发现目标的情况。 #### 处理找不到的情形 当调用 `find` 并且未找到指定模式时,它会返回特殊值 `std::string::npos`。因此,在实际编程实践中应当始终检查此返回值以确认是否真的发现了所要找的内容。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值