C++ string replace() Function
Example
Replace 5 characters, starting at position 6, with "John":
string txt = "Hello World!";
txt.replace(6, 5, "John");
cout << txt;
Definition and Usage
The replace() function replaces a part of a string with new text. You choose the part with a start position and a length.
The new text does not need to have the same length as the part it replaces.
The replace function is defined in the <string> header file.
Tip: Use find() to get the start position, like txt.replace(txt.find("World"), 5, "John");.
Syntax
string.replace(size_t start, size_t length, str);
The size_t data type is a non-negative integer.
Parameter Values
| Parameter | Description |
|---|---|
| start | Required. The position of the first character to replace. |
| length | Required. The number of characters to replace. |
| str | Required. The new text. |
Technical Details
| Returns: | A reference to the changed string. |
|---|
Related Pages
Read more about strings in our String Tutorial.