String Insert Function - C++ Programming Tutorial
C++ Course / Strings / String Insert Function

String Insert Function

BLUF: Mastering String Insert Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: String Insert Function

C++ is renowned for its efficiency. Learn how String Insert Function enables low-level control and high-performance computing in the tutorial below.

C++ String insert

This function is employed to add a new character prior to the character specified by the position pos.

Syntax

Consider two strings, str1 and str2, where 'pos' represents the position. The syntax is as follows:

Example

str1.insert(pos,str2);

Parameters

str: A string object that needs to be inserted into another string object.

It specifies the location where new content is added right before the indicated position.

subpos: It specifies the index of the initial character within the string "str" that will be inserted into another string object.

sublen: It specifies the length of characters from the string "str" to be inserted into another string object.

n : It specifies the quantity of characters to be added.

c : Character value to insert.

Example 1

Let's see the simple example.

Example

#include<iostream>
     using namespace std;
     int main()
    {
     string str1= "javat tutorial";
     cout<<"String contains :" <<str1<<'\n';
     cout<<"After insertion, String value is :"<<str1.insert(5,"point");
     return 0;
     }

Output:

Output

String contains : javat tutorial
After insertion, String value is javacpptutorial tutorial

Example 2

Let's consider a straightforward example of performing an insertion operation with the provided values of subpos and sublen.

Example

#include<iostream>
using namespace std;
int main()
{
string str1 = "C++  is a language";
string str2 = "programming";
cout<<"String contains :" <<str1<<'\n';
cout<<"After insertion, String is :"<< str1.insert(9,str2,0,11);
return 0;
}

Output:

Output

String contains C++ is a language
After insertion, String is C++ is a programming language

Example 3

Let's explore a basic example of inserting characters when the specified number of characters is provided.

Example

#include<iostream>
using namespace std;
int main()
{
string str = "Maths is favorite subject" ;
cout<<"String contains :"<<str<<'\n';
cout<<"After insertion, String contains :<<str.insert(9,"my",2);
return 0;
}

Output:

Output

String contains : Maths is favorite subject
         After insertion, String contains : Maths is my favorite subject

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience