C++ string中find() ,rfind() 等函数 用法总结及示例
来源:互联网 发布:最好用的网络机顶盒 编辑:程序博客网 时间:2024/06/06 13:18
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
示例:
#include <iostream> // std::cout#include <string> // std::stringint main (){ std::string str ("There are two needles in this haystack with needles."); std::string str2 ("needle"); // different member versions of find in the same order as above: std::size_t found = str.find(str2); if (found!=std::string::npos) std::cout << "first 'needle' found at: " << found << '\n'; found=str.find("needles are small",found+1,6); if (found!=std::string::npos) std::cout << "second 'needle' found at: " << found << '\n'; found=str.find("haystack"); if (found!=std::string::npos) std::cout << "'haystack' also found at: " << found << '\n'; found=str.find('.'); if (found!=std::string::npos) std::cout << "Period found at: " << found << '\n'; // let's replace the first needle: str.replace(str.find(str2),str2.length(),"preposition"); //replace 用法 std::cout << str << '\n'; return 0;}
结果:
first 'needle' found at: 14
second 'needle' found at: 44
'haystack' also found at: 30
Period found at: 51
There are two prepositions in this haystack with needles
其他还有 find_first_of(), find_last_of(), find_first_not_of(), find_last_not_of()
作用是查找 字符串中 任一个字符 满足的查找条件
string snake1("cobra");
int where = snake1.find_first_of("hark");
返回3 因为 "hark"中 各一个字符 在 snake1--cobra 中第一次出现的是 字符'r'(3为 cobra 中'r'的索引)
同理:
int where = snake1.find_last_of("hark");
返回4 因为 "hark"中 各一个字符 在 snake1--cobra 中最后一次出现的是 字符'a'(3为 cobra 中'r'的索引)
其他同理
- C++ string中find() ,rfind() 等函数 用法总结及示例
- C++ string中find() ,rfind() 等函数 用法总结及示例
- C++ string中find() ,rfind() 等函数 用法总结及示例
- C++ string中find() ,rfind() 等函数 用法总结及示例
- C++ string中find() ,rfind() 函数
- string类库中的find和rfind函数
- string中find函数用法
- C++ 中string.find() 函数的用法总结(转载)
- C++ 中string.find() 函数的用法总结(转载)
- C++ 中string.find() 函数的用法总结
- C++ 中string.find() 函数的用法总结
- C++ 中string.find() 函数的用法总结
- C++ 中string.find() 函数的用法总结(转载)
- C++ 中string.find() 函数的用法总结(转载)
- C++ 中string.find() 函数的用法总结
- C++ 中string.find() 函数的用法总结
- C++ 中string.find() 函数的用法总结[转]
- C++ 中string.find() 函数的用法总结(转载)
- 最效率的素数序列数组
- KMP算法 字符串匹配
- 字典树
- 第1次实验
- DP堆积木的最大高度
- C++ string中find() ,rfind() 等函数 用法总结及示例
- C++指针一个鲜见知识点
- rqnoj-356-mty的格斗-二维背包
- SWT table 设置行,列背景色,字体色
- Java一道笔试题 equals
- 银行管理系统
- VMware虚拟机磁盘压缩
- 【设计模式】Builder模式
- iOS ARC中CTCallCenter没用,无法监听电话的解决方案