Skip to content

Instantly share code, notes, and snippets.

@alco
Created February 20, 2012 14:43
Show Gist options
  • Save alco/1869521 to your computer and use it in GitHub Desktop.
Save alco/1869521 to your computer and use it in GitHub Desktop.
replace_all function in standard C++
#include <string>
#include <iostream>
#include <assert.h>
std::string replace_all(const std::string &str, const char *from, const char *to)
{
std::string result(str);
std::string::size_type
index = 0,
from_len = strlen(from),
to_len = strlen(to);
while ((index = result.find(from, index)) != std::string::npos) {
result.replace(index, from_len, to);
index += to_len;
}
return result;
}
int main(int argc, const char *argv[])
{
struct str_test_t {
const char *input;
const char *from;
const char *to;
const char *result;
} test_strings[] = {
{ "a(wow)b", "wow", "...", "a(...)b" },
{ "Hello world!", " w", "d", "Hellodorld!" },
{ "a\\b\\c", "\\", "\"", "a\"b\"c" },
{ "a\\\\b\\cde\\fg", "\\", "\\\\", "a\\\\\\\\b\\\\cde\\\\fg" },
};
for (int i = 0; i < sizeof(test_strings) / sizeof(test_strings[0]); ++i) {
struct str_test_t s = test_strings[i];
std::string result = replace_all(s.input, s.from, s.to);
if (s.result != result) {
std::cout << "Assertion failed: " << s.result << " != " << result << "\n";
abort();
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment