C++ Program to Replace all occurrences of character in 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 character in string in C++

Run it Now
#include<iostream>
#include<cstring>
using namespace std;

int main() {

    char a[100];
    int i;

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

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

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

    return 0;
}

Output:

Enter a String :Sachin Tendulkar
Before Replace :Sachin Tendulkar
After Replace :S@chin Tendulk@r