INSERT()
This is a member function used with containers like std::string
to add characters or substrings at a specific position without replacing existing content. This method is particularly useful when you want to insert text dynamically such as adding a middle name, inserting punctuation, or modifying strings during input processing while preserving the original text around the insertion point. The insert()
function takes an index or an iterator to specify the insertion location and can add single characters, C-style strings, or other std::string
objects. It shifts the existing characters to the right to accommodate the new content and returns a reference to the modified string. Overall, insert()
provides a flexible and efficient way to modify strings by inserting new data precisely where needed.
stringName.insert(position, "textToInsert");
* position: the index at which to insert new text
#include <iostream> // For input and output
#include <string>
using namespace std;
int main()
{
string fullName = "John Doe"; // Original string
fullName.insert(5, "Michael "); // Insert "Michael " after "John "
cout << "Updated Full Name: " << fullName << endl; // Display result
return 0; // End of program
}
OUTPUT:
Updated Full Name: John Michael Doe
Last updated