C++ .insert()
In C++, .insert() is a method used to insert characters, substrings, or ranges into a string at a specified position. Unlike .append(), which only adds content to the end, .insert() allows placing new data at any point within the string. It is commonly used in formatting output, inserting delimiters, modifying user input, or dynamically building strings during parsing and text processing tasks.
Syntax
string.insert(pos, str);
string.insert(pos, str, subpos, sublen);
string.insert(pos, n, char);
string.insert(iterator, char);
string.insert(iterator, n, char);
template<class InputIterator>
string.insert(iterator, InputIterator first, InputIterator last);
Parameters:
pos: The index position in the string where the insertion begins.str: The string or character array to insert.subpos: The starting position instrfor partial insertion.sublen: The number of characters to insert fromstrstarting atsubpos.n: The number of times the character should be inserted.char: The character to be inserted.iterator: An iterator pointing to the insertion position within the string.first,last: A range of iterators defining the characters to insert.
Return value:
Returns a reference to the modified string (*this), enabling method chaining.
Example 1: Inserting a Substring
This example demonstrates inserting part of one string into another at a specific index:
#include <iostream>#include <string>using namespace std;int main () {string str1 = "Hello World!";string str2 = "Amazing ";// Inserts "Amazing " at index 6 in str1str1.insert(6, str2);cout << str1;return 0;}
The output produced by this code is:
Hello Amazing World!
Example 2: Inserting a Portion of a String
This example takes a portion of one string and inserts it into another string at a specific position:
#include <iostream>#include <string>using namespace std;int main() {string str1 = "C++ is great!";string str2 = "really awesome and ";// Inserts 8 characters starting from index 7 of str2 into str1 at position 7str1.insert(7, str2, 7, 8);cout << str1;return 0;}
The output produced by this code is:
C++ is awesome great!
Codebyte Example: Inserting Multiple Characters
This codebyte demonstrates inserting multiple characters at a specific position in a string:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours