replace函数

来源:互联网 发布:智慧树网络课 编辑:程序博客网 时间:2024/06/16 12:13

#include<cassert>

#include<string>

using namespace std;

int main()

{

string A("A piece of text");

string tag("$tags");

s.insert(8,tag+' ');//s.insert(pos,cplenpos的元素之前插入cp所指向数组的前leng个字符

//s.insert(pos,cp)在下表为pos的元素之前插入cp所指向的一空字符结束的字符串副本

assert(s=="A piece $tags text")

int start=s.find(tag);

assert(start==8)

assert(tag.size()==5);

s.replace(start,tag.size(),"ellothere");

assert(s=="A piece hello there oftext");

}

//replace()函数用来改写字符,replace版本有很多重载版本,最简单的版本用了3个参数,第一个参数用于指示从什么位置开始改写第二个参数用于指示从原字符串中删除多少字符

//字符串(它所包含的字符数可以与被删除的字符数不同)

#include<cassert>

#include<iostream>

#include<string>

#includ<cstddef>//for size_t;

using namespace std;

void replaceChars(string &modify,conststring findme,string newchars)

{

size_t i=modify.find(findme,,0);

if(i!=string::npos)

{

Modify(I,findme.size(),newchars);

 

 

}

Int main()

{

String bignews=”I though I see steil in UFO”;

“I have been working too hard”;

String replacement(“wig”);

String findme(“UFO”);

 

replaceChars(bignews findme,replacement)

assert(bignew=”I thought I see steil inwigin a “

“wig .I have been working too hard”)

}

replaceAllstring类中一个字符替换字符传中各处出现的令一个字符

#include<string>

#include<iostream>

using namespace std;

 

string&replaceALL(string&context,string & from,string & to)

{

      size_tlookhere=0;

      size_tfoundhere;

      while((foundhere=context.find(from,lookhere)!=string::npos)

      {

             context.replace(lookhere,from.size(),to);

             lookhere=foundhere+to.size();

      }

      returncontext

}

void main()

{

      stringtext="a man,a plan,a canal, Pannel";

      replaceALL(text,"an","xxx");

 

 

}

原创粉丝点击