malic-2020年寒假热身-03 - Virtual Judge
数组解决
while((str[item]=getchar())!='\n')
strncmp(str+i,"apple",5)==0
strncpy(str+applePos[i],"peach",5)
#include<bits/stdc++.h>
using namespace std;
char str[1001];
int main(){
vector<int> applePos,peachPos;
int item=0;
while((str[item]=getchar())!='\n'){
item++;
}
for(int i=0;i<item;i++){
if(strncmp(str+i,"apple",5)==0) applePos.push_back(i);
if(strncmp(str+i,"peach",5)==0) peachPos.push_back(i);
}
for(int i=0;i<applePos.size();i++){
strncpy(str+applePos[i],"peach",5);
}
for(int i=0;i<peachPos.size();i++){
strncpy(str+peachPos[i],"apple",5);
}
for(int i=0;i<item;i++) cout<<str[i];
cout<<endl;
}
字符串解决
str.substr(i,5)=="apple"
str.replace(applePos[i],5,"peach")
#include<bits/stdc++.h>
using namespace std;
int main(){
string str;
vector<int> applePos,peachPos;
getline(cin,str);
for(int i=0;i<str.length();i++){
if(str.substr(i,5)=="apple") applePos.push_back(i);
if(str.substr(i,5)=="peach") peachPos.push_back(i);
}
for(int i=0;i<applePos.size();i++){
str.replace(applePos[i],5,"peach");
}
for(int i=0;i<peachPos.size();i++){
str.replace(peachPos[i],5,"apple");
}
cout<<str<<endl;
}
发现自己傻了
#include<bits/stdc++.h>
using namespace std;
int main(){
char str[1001];
int i=0;
while((str[i]=getchar())!='\n'){
i++;
}
for(int i=0;i<strlen(str)-1;i++){
if(strncmp(str+i,"apple",5)==0) strncpy(str+i,"peach",5);
else if(strncmp(str+i,"peach",5)==0) strncpy(str+i,"apple",5);
}
cout<<str;
}
#include<bits/stdc++.h>
using namespace std;
int main(){
string str;
getline(cin,str);
for(int i=0;i<str.length();i++){
if(str.substr(i,5)=="apple") str.replace(i,5,"peach");
else if(str.substr(i,5)=="peach") str.replace(i,5,"apple");
}
cout<<str<<endl;
}