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.
std::string
has areplace
method, is that what you are looking for?You could try:
I haven't tried myself, just read the documentation on
find()
andreplace()
.If you want to do it quickly you can use a two scan approach. Pseudo code:
I am not sure if this can be optimized to an in-place algo.
And a C++11 code example but I only search for one char.
I'm just now learning C++, but editing some of the code previously posted, I'd probably use something like this. This gives you the flexibility to replace 1 or multiple instances, and also lets you specify the start point.
Yes, you can do it, but you have to find the position of the first string with string's find() member, and then replace with it's replace() member.
If you are planning on using the Standard Library, you should really get hold of a copy of the book The C++ Standard Library which covers all this stuff very well.
With C++11 you can use
std::regex
like so:The double backslash is required for escaping an escape character.