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++.

using namespace std;

int main() {

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

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

    cout<<"Select a character:";

    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;


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

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.