The Wayback Machine - https://web.archive.org/web/20240619152324/https://www.geeksforgeeks.org/std-string-replace-in-cpp/
Open In App

std::string::replace() in C++

Last Updated : 08 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The string replace() function in C++ replaces each element in the part of the string in the range [first, last). It is defined inside the std::string class in C++ as a member function to provide replace functionality.

Syntax of String replace()

The syntax of std::string::replace() is as follows:

string& replace( first, last, str);

Parameters of String replace()

  • first: Iterator or index value to the starting point of the range where we want to replace the string.
  • last: Iterator or index value to the ending point of the range where we want to replace the string.
  • str: String that is to be inserted in the range first and last replacing the currently present characters.

Return Value of String replace()

  • This function returns the reference to the current string object( this ptr).

Example of String replace()

C++




// CPP code to demonstrate std::string::replace()
#include <iostream>
using namespace std;
  
// Function for demonstration
void replaceDemo(string s1, string s2, string s3, string s4)
{
    // Using positions
    cout << "Using positions:"
         << "\n";
    // Replaces 7 characters from 0th index by s2
    s1.replace(0, 7, s2);
    cout << s1 << endl;
  
    // Replaces 3 characters from 0th index with "Hello"
    s4.replace(0, 3, "Hello ");
    cout << s4 << endl;
  
    // Replaces 5 characters from 6th index of s4 with
    // 5 characters from 0th of s3
    s4.replace(6, 5, s3, 0, 5);
    cout << s4 << endl;
  
    // Replaces 5 characters from 6th index of s4 with
    // 6 characters from string "to all"
    s4.replace(6, 5, "to all", 6);
    cout << s4 << endl;
  
    // Replaces 1 character from 12th  index of s4 with
    // 3 copies of '!'
    s4.replace(12, 1, 3, '!');
    cout << s4 << endl;
  
    // Using iterators
    cout << "\nUsing iterators:"
         << "\n";
    // Replaces whole s2 string with s3
    s2.replace(s2.begin(), s2.end(), s3);
    cout << s2 << "\n";
  
    // Replaces 13 characters from begin of s1 with string
    // "Example"
    s1.replace(s1.begin(), s1.begin() + 13, "Example");
    cout << s1 << "\n";
  
    // Replace last 7 characters of s4 with first 12
    // characters of the string "geeks from- here"
    s4.replace(s4.end() - 7, s4.end(), "geeks from- here",
               12);
    cout << s4 << "\n";
  
    // Replaces last character with complete s2 string from
    // s2.begin() till s2.end()
    s4.replace(s4.end() - 1, s4.end(), s2.begin(),
               s2.end());
    cout << s4 << "\n";
  
    // Replaces portion of string s4 starting from 5
    // characters from s4.begin() to 15 characters from
    // s4.begin() with 2 occurrences of ','
    s4.replace(s4.begin() + 5, s4.begin() + 15, 2, ',');
    cout << s4 << "\n";
}
  
// Driver code
int main()
{
    string s1 = "Example of replace";
    string s2 = "Demonstration";
    string s3 = "GeeksforGeeks";
    string s4 = "HeyWorld !";
  
    replaceDemo(s1, s2, s3, s4);
    return 0;
}


Output

Using positions:
Demonstration of replace
Hello World !
Hello Geeks !
Hello to all !
Hello to all!!!!

Using iterators:
GeeksforGeeks
Example of replace
Hello to geeks from- 
Hello to geeks from-GeeksforGeeks
Hello,,from-GeeksforGeeks

Related Article : std::string::replace_copy(), std::string::replace_copy_if
This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org.

 



Similar Reads

std::fixed, std::scientific, std::hexfloat, std::defaultfloat in C++
Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are placed on the output stream. There are two types of floating point manipulators namely, fixed floating point and scientific floating point. These all are defined in header &lt;iostream&gt;. Use of precision : In the default floati
3 min read
std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++ String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let's see a few of the functionalities string class provides. Header File &lt;string&gt; String Functionalities The
6 min read
std::oct , std::dec and std::hex in C++
This function is used to set the base to octal, decimal or hexadecimal. It sets the basefield format flag for the str stream to the specified base std::oct : When basefield is set to octal, integer values inserted into the stream are expressed in octal base (i.e., radix 8). For input streams, extracted values are also expected to be expressed in oc
2 min read
std::stod, std::stof, std::stold in C++
std::stod() : It convert string into double. Syntax: double stod( const std::string&amp; str, std::size_t* pos = 0 ); double stod( const std::wstring&amp; str, std::size_t* pos = 0 ); Return Value: return a value of type double Parameters str : the string to convert pos : address of an integer to store the number of characters processed. This param
3 min read
std::setbase, std::setw , std::setfill in C++
The useful input/output manipulators are std::setbase, std::setw and std::setfill. These are defined in and are quite useful functions. std::base : Set basefield flag; Sets the base-field to one of its possible values: dec, hex or oct according to argument base.Syntax : std::setbase (int base);decimal : if base is 10hexadecimal : if base is 16octal
3 min read
std::replace and std::replace_if in C++
std::replace Assigns new_value to all the elements in the range [first, last) that compare to old_value. The function use operator == to compare the individual elements to old_value Function Template : void replace (ForwardIterator first, ForwardIterator last, const T&amp; old_value, const T&amp; new_value) first, last : Forward iterators to the in
4 min read
std::string::remove_copy(), std::string::remove_copy_if() in C++
remove_copy() It is an STL function in c++ which is defined in algorithm library. It copies the elements in the range [first, last) to the range beginning at result, except those elements that compare equal to given elements. The resulting range is shorter than [first,last) by as many elements as matches in the sequence, which are "removed". The re
4 min read
std::string::crbegin() and std::string::crend() in C++ with Examples
std::string::crbegin() The std::string::crbegin() is a string class built-in function that returns a constant reverse iterator referring to the last element in the string. Using this iterator starts the string traversal from the end of the string. Header File: #include &lt;string&gt; Template Class: template &lt;class C&gt; auto crbegin( const C
3 min read
std::string::replace_copy(), std::string::replace_copy_if in C++
replace_copy replace_copy() is a combination of copy() and replace(). It copies the elements in the range [first, last) to the range beginning at result, replacing the appearances of old_value by new_value.The range copied is [first, last), which contains all the elements between first and last, including the element pointed by first but not the el
4 min read
std::string::append vs std::string::push_back() vs Operator += in C++
To append characters, you can use operator +=, append(), and push_back(). All of them helps to append character but with a little difference in implementation and application. Operator += : appends single-argument values. Time complexity : O(n)append() : lets you specify the appended value by using multiple arguments. Time complexity: O(n)push_back
6 min read
Article Tags :
Practice Tags :