C++ string insert() Function
Example
Insert a comma at position 5:
string txt = "Hello World!";
txt.insert(5, ",");
cout << txt;
Definition and Usage
The insert() function inserts text into a string, at a given position. The characters after that position move to the right.
You can insert a string, or a number of copies of one character.
The insert function is defined in the <string> header file.
Syntax
string.insert(size_t start, str);
string.insert(size_t start, size_t count, char c);
Use one of the two forms. The size_t data type is a non-negative integer.
Parameter Values
| Parameter | Description |
|---|---|
| start | Required. The position to insert the text at. |
| str | Required. The string to insert. |
| count | Required. The number of times to insert the character. |
| c | Required. The character to insert. |
Technical Details
| Returns: | A reference to the changed string. |
|---|
Related Pages
Read more about strings in our String Tutorial.