Replacing a substring within a std::string
with another string is accomplished using the replace()
method. This method allows you to specify the starting position, the number of characters to replace, and the new substring.
The replace()
method requires three arguments: the starting position, the number of characters to replace, and the new substring. For example:
#include <iostream>
#include <string>
int main(){
std::string Greeting{"Hello World!"};
Greeting.replace(6, 5, "Everyone");
std::cout << Greeting;
}
Hello Everyone!
The new substring does not need to be the same length as the substring being replaced. The string will adjust its size accordingly.
#include <iostream>
#include <string>
int main(){
std::string Greeting{"Hello Everyone!"};
Greeting.replace(6, 8, "World");
std::cout << Greeting;
}
Hello World!
You can also use iterators to specify the range of characters to replace. This can be useful when working with more complex string manipulations.
#include <iostream>
#include <string>
int main() {
std::string Greeting{"Hello World!"};
std::string Replacement{"Everyone"};
Greeting.replace(Greeting.begin() + 6,
Greeting.begin() + 11,
Replacement);
std::cout << Greeting;
}
Hello Everyone!
For more control, you can replace a substring from another string by specifying the starting position and length within the new string.
#include <iostream>
#include <string>
int main() {
std::string Greeting{"Hello World!"};
std::string Replacement{"Greetings Earthlings"};
Greeting.replace(6, 5, Replacement, 10, 5);
std::cout << Greeting;
}
Hello Earth!
The replace()
method is powerful and flexible, making it easy to modify parts of a std::string
as needed.
Answers to questions are automatically generated and may not have been reviewed.
std::string
ObjectsA practical guide covering the most useful methods and operators for working with std::string
objects and their memory