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.replace("$name", "Somename");
But I would like to use the Standard C++ libraries.
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.replace("$name", "Somename");
But I would like to use the Standard C++ libraries.
To have the new string returned use this:
If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:
Tests:
Output:
I use generally this:
It repeatedly calls
std::string::find()
to locate other occurrences of the searched for string untilstd::string::find()
doesn't find anything. Becausestd::string::find()
returns the position of the match we don't have the problem of invalidating iterators.There's a function to find a substring within a string (
find
), and a function to replace a particular range in a string with another string (replace
), so you can combine those to get the effect you want:In response to a comment, I think
replaceAll
would probably look something like this:This sounds like an option
string.replace(string.find("%s"), string("%s").size(), "Something");
You could wrap this in a function but this one-line solution sounds acceptable. The problem is that this will change the first occurence only, you might want to loop over it, but it also allows you to insert several variables into this string with the same token (
%s
)If all strings are std::string, you'll find strange problems with the cutoff of characters if using
sizeof()
because it's meant for C strings, not C++ strings. The fix is to use the.size()
class method ofstd::string
.That replaces sHaystack inline -- no need to do an = assignment back on that.
Example usage: