练习 9.43:编写一个函数,接受三个string参数s、oldVal和newVal。使用迭代器及insert和erase函数将s中所有oldVal替换为newVal。测试你的程序,用它替换通用的简写形式,如,将"tho"替换为"though",将"thru"替换为"through"。
注意:以下代码用codeblocks编译无法通过,用visual studio2015编译可以通过。
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
void replace_char(string &s, const string &oldVal, const string &newVal)
{
auto iter = s.begin();
//循环判定条件中,s.end()一定要减去oldVal.size(),否则程序虽然能够编译成功,但运行时会出错,因为循环主体中的iter + oldVal.size()会越界。
//循环判定需要使用"<=",而不使用"!=",否则s的最后一个字符会无法替换。
while (iter <= s.end() - oldVal.size())
{
if (string(iter, iter + oldVal.size()) == oldVal)
{
iter = s.erase(iter, iter + oldVal.size());
iter = s.insert(iter, newVal.cbegin(), newVal.cend());
iter += newVal.size();
}
else
++iter;
}
}
int main()
{
//以下字符串中的"thotho"是特意用来测试待替换string连在一起的情况的。
string s("What do I discover thotho? It looks as tho it might clear up tho.");
//string oldVal("tho"), newVal("though");
cout << "原string:" << s << "\n替换后为:";
replace_char(s, "tho", "though");
cout << s << endl;
//以下字符串用于测试函数能否正确地替换最后一个字符
string ss("who I am?");
cout << "原string:" << ss << "\n替换后为:";
replace_char(ss, "?", "...");
cout << ss << endl;
return 0;
}
练习 9.44:重写上一题的函数,这次使用一个下标和replace。
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
void replace_char(string &s, string oldVal, string newVal)
{
int i = 0;
while (i != s.size())
if (s.substr(i, oldVal.size()) == oldVal)
{
s.replace(i, oldVal.size(), newVal);
i += newVal.size();
}
else
++i;
}
int main()
{
//以下字符串中的"thotho"是特意用来测试待替换string连在一起的情况的。
string s("What do I discover thotho? It looks as tho it might clear up tho.");
//string oldVal("tho"), newVal("though");
cout << "原string:" << s << "\n替换后为:";
replace_char(s, "tho", "though");
cout << s << endl;
//以下字符串用于测试函数能否正确地替换最后一个字符
string ss("who I am?");
cout << "原string:" << ss << "\n替换后为:";
replace_char(ss, "?", "...");
cout << ss << endl;
return 0;
}