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
susing thelength()method and store it inl. - Loop through the string using a
forloop, checking each character.- If the character
s[i]matchesc2(the character to be replaced), it is replaced withc1.
- If the character
- After replacing all instances of
c2withc1, 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
stris initialized with"OcianLabz". c1is assigned the character'e', which is the character that will replace'i'(represented byc2).- The original string is printed using
cout. - The
replacefunction is called with the stringstr,c1('e'), andc2('i'). The function returns a new string with all instances of'i'replaced by'e', and the result is printed.
