String replace() function in C++

In this tutorial, we will learn about the string replace() function in C++ with a suitable example.

So continue reading it…

The replace() function replaces the particular part of the string that starts at index value (character position) ind having a length len.

Index value specifies the character position from which we will start replacing the characters.
The length specifies the number of characters needs to be replaced.
Let us take two strings string1 and string2.

The syntax for C++ string replace() function is:

string1.replace(ind, len, string2);


string: Object of the string.
ind: The index value where a character is to be replaced.
len: Stores data about the number of characters to be erased by another string.

Return value:

The replace() function does not have any return value.

string replace() function in C++

Now, let us write the code to illustrate the same.
Note: I have written this code using an online IDE platform.

#include <iostream>  
using namespace std;  
int  main()  
 string string1 = "C++ is a difficult programming language";  
 string string2 = "an easy";  
 cout << "Before replacing, the string is : "<<string1<<'\n';  
 cout << "After replacing, the new string is : "<<string1<<'\n';  
 return 0;  

And the output of our program is:

Before replacing, the string is : C++ is a difficult programming language                                                      
After replacing, the new string is : C++ is an easy programming language

Explanation of the program:

In this code, first of all, we declared string 1, i.e. the original string and the string 2, i.e. the string which will replace the particular part of the string 1.  We print the original string first, then we use the replace() function and specify the index value (position), length, and string object. After replacing, we print the new string on the screen.

I hope this will help you to solve your problem.

You can also read:

C++ Math nexttoward() function with example

C++ Deque cbegin( ) function

Leave a Reply

Your email address will not be published. Required fields are marked *