输入一句话,再输入刚才那句话中你想更改的字符串,然后输入要替换的字符串,然后输出。
以下是自己看了书上的例子,自己写的代码,结果悲剧。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text;
cout << "Enter a string terminated by #: " << endl;
getline(cin, text, '#');
string word;
cout << "Enter the word to be replaced: " << endl;
cin >> word;
string replacement;
cout << "Enter the replacement word: " << endl;
cin >> replacement;
if (word == replacement)
cout << "The word and its replacement are the same. " << endl;
size_t start = text.find(word);
while (start != string::npos)
{
text.replace(start, word.length(), replacement);
cout << "Your string is now: " << text <<endl;
};
return 0;
}
输出结果惊人:(无法上图,算了,总之是一个循环无限下去)
如果输入的待更改字符串与替换字符串相同的话,即word == replacement:
所以对照一下书上代码,发现症结所在。
第一个问题;while循环中,首先看条件,只要start不等于string::npos就一直循环,问题就出在这里了,为什么它会一直搞下去,因为,没有检测到string::npos。所以应该在循环中加入一个递增,这也是基本常识。
start = text.find(word, start + replacement.length()); |
还有,需要把while循环中的输出写到结尾,如果text中有多个要替换的word输出会出现多个渐变的输出结果,而我们需要的是最后一个结果。
text.replace(start, word.length(), replacement); cout << "Your string is now: " << text <<endl; start = text.find(word, start + replacement.length()); |
第二个问题;同样if循环中,既然出错了就需要一个终止。
cout << "The word and its replacement are the same. " << endl; exit(1); |
最终代码更改以后
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text;
cout << "Enter a string terminated by #: " << endl;
getline(cin, text, '#');
string word;
cout << "Enter the word to be replaced: " << endl;
cin >> word;
string replacement;
cout << "Enter the replacement word: " << endl;
cin >> replacement;
if (word == replacement)
{
cout << "The word and its replacement are the same. " << 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 << "Your string is now: " << text <<endl;
return 0;
}
得以实现——牛刀小试,以失败告终!!