思路:先写好框架。将框架转换成字符串形式。
处理引号、换行:这两种字符一般 在字符串会转义,因此替换时不能直接写,要用ASCII值表示。
#include <iostream>
using namespace std;
string replace_all(string src, char tc, string const & w)
{
string s(src);
string t(1, tc);
unsigned int pos = s.find(t), t_size = t.size(), r_size = w.size();
while(pos != std::string::npos){
s.replace(pos, t_size, w);
pos = s.find(t, pos + r_size );
}
return s;
}
int main()
{
char const *s = "#include <iostream>\nusing namespace std;\n\nstring replace_all(string src, char tc, string const & w)\n{\n string s(src);\n string t(1, tc);\n unsigned int pos = s.find(t), t_size = t.size(), r_size = w.size();\n while(pos != std::string::npos){\n s.replace(pos, t_size, w);\n pos = s.find(t, pos + r_size );\n }\n return s;\n}\n\nint main()\n{\n char const *s = |@|;\n char const q[] = {34,0};\n char const n[] = {92,110,0};\n cout << replace_all(replace_all(s,124,q), 64, replace_all(s, 10, n));\n}\n";
char const q[] = {34,0};
char const n[] = {92,110,0};
cout << replace_all(replace_all(s,124,q), 64, replace_all(s, 10, n));
}