In this C++ tutorial, you will learn how to insert a given character at specific index in the string using string::insert() function, with examples.

Insert Character in String at Specific Index

string::insert() function inserts a given character at specific index in this string.

Syntax

The syntax to insert character ch at index i in the string str is

</>
Copy
str.index(i, ch)

Examples

1. Insert char ‘m’ at index=2 in the string

In the following program, we take a string: str and insert the character "m" at index 2 using string::insert() function.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
    string str = "apple";
    str.insert(2, "m");
    cout << str << endl;
}

Output

apmple
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned how to insert given character at specific index in this string using string::insert() function, with examples.