In this C++ tutorial, you will learn how to replace specific character with another character in a string using string::replace() function, with example programs.

Replace specific character with another character in string

To replace specific character with another character in a string in C++, we can use std::string::replace() method of the algorithm library.

replace() method takes the beginning position of search in string, ending position of search in string, search character, and replacement characters as arguments in the respective order.

The syntax of the statement to replace the character search with replacement character replacement in str is

</>
Copy
replace(str.begin, str.end, search, replacement);

You must include algorithm library at the starting of the program.

</>
Copy
#include <algorithm>

C++ Program

In the following program, we take a string value in str, search character in variable search, and replacement character in variable replacement. To use the replace() method, we shall include algorithm header/library in our program.

main.cpp

</>
Copy
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
   string str = "apple banana";
   char search = 'a';
   char replacement = 'v';

   replace(str.begin(), str.end(), search, replacement);
   cout << str << endl;
}

Output

vpple bvnvnv

Conclusion

In this C++ Tutorial, we learned how to replace a specific character with another, in a string, using replace() method of algorithm library.