Inserting a substring into a specific position within a std::string
is done using the insert()
method. This method modifies the original string by adding the new substring at the specified position.
The insert()
method requires two arguments: the position to insert the substring and the substring itself. For example:
#include <iostream>
#include <string>
int main(){
std::string Greeting{"Hello!"};
Greeting.insert(5, " World");
std::cout << Greeting;
}
Hello World!
You can also insert a single character at a specific position.
#include <iostream>
#include <string>
int main(){
std::string Greeting{"Hell World!"};
Greeting.insert(4, "o");
std::cout << Greeting;
}
Hello World!
The insert()
method can also insert multiple characters at once.
#include <iostream>
#include <string>
int main(){
std::string Greeting{"Hello!"};
Greeting.insert(5, "!!!", 2);
std::cout << Greeting;
}
Hello!!!
You can also insert a substring from another string by specifying the starting position and length.
#include <iostream>
#include <string>
int main(){
std::string Greeting{"Hello "};
std::string Name{"Alice Wonderland"};
Greeting.insert(6, Name, 0, 5);
std::cout << Greeting;
}
Hello Alice
In summary, the insert()
method is versatile and allows you to add substrings, single characters, or multiple characters to a std::string
at any position you need.
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