What is the string replace function in C++?
The replace method of the String class replaces a portion of a string that begins at a specific starting position and spans a specific number of characters.
The starting position, the number of characters, and the respective replacement string are all passed as arguments.
Syntax
Code
The example below shows how the replace method is used to modify strings:
#include <iostream>#include <string>using namespace std;int main() {string str = "Welcome to Educative!";// replace "come" of "Welcome" with "abcd".// starting position = 3, length = 4,// replacement string = "abcd"str.replace(3,4,"abcd");cout << str << endl;return 0;}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved