Is it possible in C++ to replace part of a string with another string?
Basically, I would like to do this:
QString string(\"hello $name\");
string.re
My own implementation, taking into account that string needs to be resized only once, then replace can happen.
template
std::basic_string replaceAll(const std::basic_string& s, const T* from, const T* to)
{
auto length = std::char_traits::length;
size_t toLen = length(to), fromLen = length(from), delta = toLen - fromLen;
bool pass = false;
std::string ns = s;
size_t newLen = ns.length();
for (bool estimate : { true, false })
{
size_t pos = 0;
for (; (pos = ns.find(from, pos)) != std::string::npos; pos++)
{
if (estimate)
{
newLen += delta;
pos += fromLen;
}
else
{
ns.replace(pos, fromLen, to);
pos += delta;
}
}
if (estimate)
ns.resize(newLen);
}
return ns;
}
Usage could be for example like this:
std::string dirSuite = replaceAll(replaceAll(relPath.parent_path().u8string(), "\\", "/"), ":", "");