然而沼跃鱼早已看穿了一切——字符串替换

时间:2021-07-25 08:54:30

时间限制:1000ms
单点时限:1000ms
内存限制:256MB
描述
marshtomp.jpg

fjxmlhx每天都在被沼跃鱼刷屏,因此他急切的找到了你希望你写一个程序屏蔽所有句子中的沼跃鱼(“marshtomp”,不区分大小写)。为了使句子不缺少成分,统一换成 “fjxmlhx” 。

输入
输入包括多行。

每行是一个字符串,长度不超过200。

一行的末尾与下一行的开头没有关系。

输出
输出包含多行,为输入按照描述中变换的结果。

样例输入
The Marshtomp has seen it all before.
marshTomp is beaten by fjxmlhx!
AmarshtompB
样例输出
The fjxmlhx has seen it all before.
fjxmlhx is beaten by fjxmlhx!
AfjxmlhxB

想法:1.大小写要考虑;准备两个s,一个全转化为小写字母后再在另一个字符串中替换。
2.替换后有缩进,一个句子中可能出现多个‘marshtomp’
方法一:

#include<iostream>
#include<string>
using namespace std;
void replace(string s){
if(s.size()<=0)
return;
int len = s.size();
string s1 = s;
for(int i = 0; i<len; i++)
{
s[i] = tolower(s[i]);
}
int t = 0;
int count = 0;
int j = 0;
while(t>=0){
count++;
t = s.find("marshtomp",j);
if(t == string::npos){
break;
}
j = t+9;
s1.replace(t-2*(count-1),9,"fjxmlhx");
}
cout<<s1<<endl;

}
int main(){
string str;
while(getline(cin,str)){//
replace(str);
}
}

方法二:

#include<iostream>
#include<string>
#include<cctype>
#include<algorithm>
using namespace std;
int main(){
string s,s1;
while(getline(cin,s)){
if(s.size()<= 0){
return 0;
}
s1 = s;
int len = s.size();
//cout<<s<<endl;
for(int i = 0; i<s.size(); i++){

s[i] = tolower(s[i]);
}
//cout<<s<<endl;
//transform(s.begin(),s.end(),s.begin(),::tolower);
int count = 0;
int t = s.find("marshtomp");
//cout<<"finding t"<<t<<endl;
while(t>=0){ //尼玛这里-1也是不为空的啊,不要以为-1就是>0就不满足while(t)
count ++;
int i = t-2*(count-1);
int j = t+9;
s1[i] = 'f';
s1[i+1] = 'j';
s1[i+2] = 'x';
s1[i+3] = 'm';
s1[i+4] = 'l';
s1[i+5] = 'h';
s1[i+6] = 'x';
//cout<<s<<endl;

t = s.find("marshtomp",j);
//cout<<t<<endl;
//system("pause");
if(t == -1){
while(j<len){
s1[j-2*count] = s1[j];
//cout<<j-2*count<<"="<<s[j-2*count]<<j<< "="<< s[j]<<endl;
j++;
}
s1[j-2*count] = '\0';

}else{
while(j<t){
s1[j-2*count] = s1[j];
j++;
}
//continue;
}

}
cout<<s1.substr(0,len-2*count)<<endl;

}
}

这个可以用C++中的string类型的内置函数,replace(),它替换完成后可以自动进行缩进,但是有两点要注意,一个是输入问题,之前用的是while(cin>>str),这样写的话,加入输入样例是“The marshtomp has seen it all before”,会被当成几个单词一次处理而不是一句话,难怪之前一直输出没有空格。正确的应该是getline(cin,str),才是输入一个句子当成一个完整的字符串。第二个问题是要考虑缩进后再替换的起始位置。

如果不用string的replace函数,那么就像剑指offer中的空格替换成’%20’一样,先计算一下缩进,再替换。