C++ Program to Replace all occurrences of a character in the string


In this program, You will learn how to Replace all occurrences of character in string in C++.


Enter a String :Sachin Tendulkar

/* Replace a to @ */

After Replace: S@chin Tendulk@r

Example: How to Replace all occurrences of a character in string in C++.

#include<iostream>
#include<cstring>
using namespace std;

int main() {

    char a[100],r,sel;
    int i;

    cout << "Enter a string:";
    cin.getline(a, 100);

    cout<<"Select a character:";
    cin>>sel;

    cout << "Enter a character for Replace:";
    cin >>r;

    i = strlen(a);
    cout << "Before Replace:" << a;

    /* Replace a to @ */
    for (int j = 0; j < i; j++) {
        if (a[j]==sel) {
            a[j] = r;
        }
    }
    cout << "\nAfter Replace:" << a;

    return 0;
}

Output:

Enter a string:Xiith.com
Select a character:i
Enter a character for Replace:#
Before Replace:Xiith.com
After Replace:X##th.com