Skip to content

Instantly share code, notes, and snippets.

@Shitaibin
Last active April 6, 2016 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shitaibin/d39b7511ce2162f7a5ba518678ac7148 to your computer and use it in GitHub Desktop.
Save Shitaibin/d39b7511ce2162f7a5ba518678ac7148 to your computer and use it in GitHub Desktop.
C++字符串替换函数
// 参考《C++编程思想卷2》
#include <iostream>
#include <string>
using namespace std;
string& replace_all(string& context, const string& from, const string& to) {
size_t look_here = 0;
size_t found_here;
while ((found_here = context.find(from, look_here)) != string::npos) {
context.replace(found_here, from.size(), to);
look_here = found_here + to.size();
}
return context;
}
void test(string s, string from, string to, string result) {
string ret = replace_all(s, from, to);
if (ret != result) {
cout << "fail case:" << endl;
cout << s << " " << from << " " << to << endl;
cout << "true: " << result << endl;
cout << "false: " << ret << endl;
cout << "--------------" << endl << endl;
}
}
int main()
{
test("", "a", "b", ""); // empty
test("ab", "a", "b", "bb"); // equal repalce
test("abcdabd", "abc", "xf", "xfdabd"); // short repalce
test("xabcdabd", "ab", "AB", "xABcdABd"); // equal, down to upper
test("abcd", "xy", "z", "abcd"); // not find
test("abcdabd", "ab", "xyzab", "xyzabcdxyzabd"); // add same substring
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment