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:
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.
#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:
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.
#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:
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.
#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:
String contains : Maths is favorite subject
After insertion, String contains : Maths is my favorite subject