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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <string> #include <algorithm> #include <iostream> 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<<s<<endl; } return 0; } |
Comments