If s
is a std::string
, then is there a function like the following?
s.replace(\"text to replace\", \"new text\");
Not exactly that, but std::string
has many replace overloaded functions.
Go through this link to see explanation of each, with examples as to how they're used.
Also, there are several versions of string::find functions (listed below) which you can use in conjunction with string::replace
.
Also, note that there are several versions of replace
functions available from <algorithm>
which you can also use (instead of string::replace
):
Yes: replace_all is one of the boost string algorithms:
Although it's not a standard library, it has a few things on the standard library:
replace_all
nested inside a trim
). That's a bit more involved for the standard library functions.Try a combination of std::string::find and std::string::replace.
This gets the position:
std::string s;
std::string toReplace("text to replace");
size_t pos = s.find(toReplace);
And this replaces the first occurrence:
s.replace(pos, toReplace.length(), "new text");
Now you can simply create a function for your convenience:
std::string replaceFirstOccurrence(
std::string& s,
const std::string& toReplace,
const std::string& replaceWith)
{
std::size_t pos = s.find(toReplace);
if (pos == std::string::npos) return s;
return s.replace(pos, toReplace.length(), replaceWith);
}
Here's the version I ended up writing that replaces all instances of the target string in a given string. Works on any string type.
template <typename T, typename U>
T &replace (
T &str,
const U &from,
const U &to)
{
size_t pos;
size_t offset = 0;
const size_t increment = to.size();
while ((pos = str.find(from, offset)) != T::npos)
{
str.replace(pos, from.size(), to);
offset = pos + increment;
}
return str;
}
Example:
auto foo = "this is a test"s;
replace(foo, "is"s, "wis"s);
cout << foo;
Output:
thwis wis a test
Note that even if the search string appears in the replacement string, this works correctly.