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'的索引)
 
其他同理

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 脚上起水泡怎么办很痒 手冻了起小疙瘩怎么办 手过敏起小疙瘩怎么办 闲鱼交易被骗了怎么办 闲鱼交换被骗了怎么办 闲鱼转账被骗了怎么办 闲鱼买家被骗了怎么办 闲余资金保护中怎么办 颈椎引起的手麻怎么办 遇到不明理的人怎么办 开心网账号忘了怎么办 失眠十多年了怎么办呀 两眼角下面长斑怎么办 放环脸上会长斑怎么办 脸上起黑色的斑怎么办 经常熬夜脸上长斑怎么办 最近脸上长了好多斑怎么办 脸颊突然长斑了怎么办 长斑怎么办能根治吗 脸突然长斑了怎么办 生气后脸上长斑怎么办 脸上长了座疮怎么办 喝了啤酒吃柿子怎么办 脸上长了痤疮该怎么办 脸上老长闭口痘怎么办 右脸颊一直长痘怎么办 痘痘粉刺反复长怎么办 长痘留下的红印怎么办 熬夜长出的痘痘怎么办 脸上两边长痘痘怎么办 我左脸比右脸大怎么办 左脸莫名肿了怎么办 牙疼得半边脸痛怎么办 手和脸突然发麻怎么办 右半边脸麻木了怎么办 左边脸突然肿了怎么办 左半边脸皮肤疼怎么办 脸内侧的肉肿了怎么办 上火引起的脸肿怎么办 脸肿里面有硬块怎么办 内分泌失调引起的肥胖怎么办