Skip to content →

Tag: STL

C++ STL Notes: String Replacement

Macro

You are asked to do some replacements on a string. Can you work it out?

Input and Output

 

Each test case will begin with a string in a single line, and followed by an integer N which means the number of replacements. The next N lines will give you two strings s1, s2, you should replace all the s1 into s2. For more details, see the
sample below.

Sample Input

 

abc
3
a b
bb a
c d
aaabaaaa
1
aa a

Sample Output

 

ad
aabaa

Note:
For the first sample:
After the first replacement, the string will be bbc.
After the second replacement, the string will be ac.
At last, the string will be ad.

My Code:

#include 
#include 
#include 

using namespace std;

void myreplace(string & strBig, const string & strsrc, const string &strdst)
{
string::size_type pos=0;
string::size_type srclen=strsrc.size();
string::size_type dstlen=strdst.size();
while( (pos=strBig.find(strsrc, pos)) != string::npos)
{
strBig.replace(pos, srclen, strdst);
pos += dstlen;
}
}

int main(int argc, char** argv)
{
string s;
while(cin>>s)
{
int n;
string s1,s2;
cin>>n;
while(n–)
{
cin>>s1>>s2;
myreplace(s,s1,s2);
}
cout<

Leave a Comment