c++ string的查找与替换

功能描述:
查找:查找指定字符串是否存在
替换:在指定的位置替换字符串
函数原型:
int find(const string& str, int pos = 0) const; //查找str第一次出现位置,pos开始查找
int find(const char* s, int pos = 0) const; //查找s第一次出现位置,pos开始查找
int find(const char* s, int pos, int n) const; //pos位置查找s的前n个字符第一次位置
int find(const char c, int pos = 0) const; //查找字符c第一次出现位置
int rfind(const string& str, int pos = npos) const; //查找str最后一次位置,pos开始查找
int rfind(const char* s, int pos = npos) const; //查找s最后一次出现位置,pos开始查找
int rfind(const char* s, int pos, int n) const; //pos查找s的前n个字符最后一次位置
int rfind(const char c, int pos = 0) const; //查找字符c最后一次出现位置
string& replace(int pos, int n, const string& str); //替换从pos开始n个字符为字符串str
string& replace(int pos, int n,const char* s); //替换从pos开始的n个字符为字符串s

注意,rfind是从左往右找,同时pos位置指的是从左往右忽略到第几个位置,但是最终得到的结果是正常从右往左的序列结果,比如rfind(“a”,0)最后得到的结果一定是0或者-1,因为其他位置的都被忽略掉了。另一方面,注意replace的时候,替换的数量是输入的,但是实际插入的结果受实际输入制约,比如替换3个,但是输入了四个,结果也是替换掉了三个,但是插入了四个

 

  string s1 = "abcdefgaaa";
  int pos = s1.find("d1",0);
  cout << pos <<endl;
  int poe = s1.rfind("de",7);
  cout << poe <<endl;
  s1.replace(1,3,"11111");
  cout << s1 <<endl;
  s1.replace(6,3,"1");
  cout << s1 <<endl;
 
-1
3
a11111efgaaa
a111111aaa
posted @   纸包鱼  阅读(877)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示