Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Replace character in a string

In this example, I will show you how to replace character in a string

#include <iostream>
#include <string.h>
#include <bits/stdc++.h>
using namespace std;

string replace(string s, char c1, char c2){
    int l = s.length();
    for(int i = 0; i < l; i++){
        if(s[i] == c2)
            s[i] = c1;
    }
    return s;
}

int main(){
    string str = "OcianLabz";
    cout<<"Input String : "<<str<<endl;
    char c1 = 'e', c2 = 'i';
    cout<<"After Replace string : "<<replace(str,c1,c2);
    return 0;
}

Output:

Input String : OcianLabz
After Replace string : OceanLabz

Explanation:

Step1 : replace Function

string replace(string s, char c1, char c2){
    int l = s.length();
    for(int i = 0; i < l; i++){
        if(s[i] == c2)
            s[i] = c1;
    }
    return s;
}

This function takes three parameters:

  • s: The input string.
  • c1: The character to replace with.
  • c2: The character to be replaced.

The steps:

  • Calculate the length of the string s using the length() method and store it in l.
  • Loop through the string using a for loop, checking each character.
    • If the character s[i] matches c2 (the character to be replaced), it is replaced with c1.
  • After replacing all instances of c2 with c1, the modified string is returned.

Step2 : main() Function

int main(){
    string str = "OcianLabz";
    cout<<"Input String : "<<str<<endl;
    char c1 = 'e', c2 = 'i';
    cout<<"After Replace string : "<<replace(str,c1,c2);
    return 0;
}

In the main() function:

  • A string str is initialized with "OcianLabz".
  • c1 is assigned the character 'e', which is the character that will replace 'i' (represented by c2).
  • The original string is printed using cout.
  • The replace function is called with the string str, c1 ('e'), and c2 ('i'). The function returns a new string with all instances of 'i' replaced by 'e', and the result is printed.

    Leave a Reply

    Your email address will not be published.

    Need Help?