64,637
社区成员
发帖
与我相关
我的任务
分享
//程序用另一个单词代替指定单词
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main(){
//从键盘读取字符串
string text;
cout<<"please Enter a string terminated by #: ";//terminated终止
std::getline(cin,text,#);
//获得要被取代的单词
string word;
cout<<"please Enter the word to be replaced: ";//replaced取代
cin>>word;
//得到更换的单词
string replacement;
cout<<endl<<"Enter the replacement word: ";
cin>>replacement;
if(word==replacement){
cout<<endl
<<"The word and it's replacement are the same."<<endl
<<"Operation aborted."<<endl;
exit(1);
}
size_t start=text.find(word);
while(start!=string::npos){
text.replace(start,word.length(),replacement);
start=text.find(word,start+replacement.length());
}
cout<<endl
<<"Your string is now: "<<endl
<<text<<endl;
return 0;
}
std::getline(cin,text, '#');
//程序用另一个单词代替指定单词
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main(){
//从键盘读取字符串
string text;
cout<<"please Enter a string terminated by #: ";//terminated终止
std::getline(cin,text,'#'); // 要细心:#要用'' 或者 ""扩起来,不然就成宏连接了
//获得要被取代的单词
string word;
cout<<"please Enter the word to be replaced: ";//replaced取代
cin>>word;
//得到更换的单词
string replacement;
cout<<endl<<"Enter the replacement word: ";
cin>>replacement;
if(word==replacement){
cout<<endl
<<"The word and it's replacement are the same."<<endl
<<"Operation aborted."<<endl;
exit(1);
}
size_t start=text.find(word);
while(start!=string::npos){
text.replace(start,word.length(),replacement);
start=text.find(word,start+replacement.length());
}
cout<<endl
<<"Your string is now: "<<endl
<<text<<endl;
return 0;
}