#include <string>
#include <boost/algorithm/string/replace.hpp>
///Replaces all occurences of a substring
//From http://www.richelbilderbeek.nl/CppReplaceAll.htm
const std::string ReplaceAllBoost(
std::string s,
const std::string& before,
const std::string& after)
{
return boost::algorithm::replace_all_copy(s,before,after);
}
#include <QString>
///Replaces all occurences of a substring
//From http://www.richelbilderbeek.nl/CppReplaceAll.htm
const std::string ReplaceAllQt(
std::string s,
const std::string& before,
const std::string& after)
{
QString q(s.c_str());
q.replace(before.c_str(),after.c_str());
return q.toStdString();
}
///Replaces all occurences of a substring
//From http://www.richelbilderbeek.nl/CppReplaceAll.htm
const std::string ReplaceAllStl(
std::string s,
const std::string& before,
const std::string& after)
{
while(1)
{
const int pos = s.find(before);
if (pos==-1) break;
s.replace(pos,before.size(),after);
}
return s;
}
#include <cassert>
int main()
{
//Test single char replacement
{
//s: input string
//x: expected output string
//b: before
//a: after
const std::string s = "abcdbef";
const std::string x = "a_cd_ef";
const std::string b = "b";
const std::string a = "_";
assert(ReplaceAllBoost(s,b,a) == x);
assert(ReplaceAllQt(s,b,a) == x);
assert(ReplaceAllStl(s,b,a) == x);
}
//Test single char to multiple chars replacement
{
const std::string s = "abcdbef";
const std::string x = "a__cd__ef";
const std::string b = "b";
const std::string a = "__";
assert(ReplaceAllBoost(s,b,a) == x);
assert(ReplaceAllQt(s,b,a) == x);
assert(ReplaceAllStl(s,b,a) == x);
}
//Test single char to no char replacement
{
const std::string s = "abcdbef";
const std::string x = "acdef";
const std::string b = "b";
const std::string a = "";
assert(ReplaceAllBoost(s,b,a) == x);
assert(ReplaceAllQt(s,b,a) == x);
assert(ReplaceAllStl(s,b,a) == x);
}
//Test multiple chars to multiple chars replacement
{
const std::string s = "abcdbcef";
const std::string x = "a__d__ef";
const std::string b = "bc";
const std::string a = "__";
assert(ReplaceAllBoost(s,b,a) == x);
assert(ReplaceAllQt(s,b,a) == x);
assert(ReplaceAllStl(s,b,a) == x);
}
//Test multiple chars to more chars replacement
{
const std::string s = "abcdbcef";
const std::string x = "a___d___ef";
const std::string b = "bc";
const std::string a = "___";
assert(ReplaceAllBoost(s,b,a) == x);
assert(ReplaceAllQt(s,b,a) == x);
assert(ReplaceAllStl(s,b,a) == x);
}
//Test multiple chars to single char replacement
{
const std::string s = "abcdbcef";
const std::string x = "a_d_ef";
const std::string b = "bc";
const std::string a = "_";
assert(ReplaceAllBoost(s,b,a) == x);
assert(ReplaceAllQt(s,b,a) == x);
assert(ReplaceAllStl(s,b,a) == x);
}
//Test multiple chars to no char replacement
{
const std::string s = "abcdbcef";
const std::string x = "adef";
const std::string b = "bc";
const std::string a = "";
assert(ReplaceAllBoost(s,b,a) == x);
assert(ReplaceAllQt(s,b,a) == x);
assert(ReplaceAllStl(s,b,a) == x);
}
}
|