Replace all occurrences of character X with character Y in given string
Last Updated :
05 Apr, 2023
Given a string str and two characters X and Y, the task is to write a recursive function to replace all occurrences of character X with character Y.
Examples:
Input: str = abacd, X = a, Y = x
Output: xbxcd
Input: str = abacd, X = e, Y = y
Output: abacd
Iterative Approach: The idea is to iterate over the given string and if any character X is found then replace that character with Y.
Code-
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to replace all occurrences
// of character c1 with character c2
void replaceCharacter(char* str, char c1, char c2)
{
int j, n = strlen(str);
for (int i = j = 0; i < n; i++) {
if (str[i] != c1) {
str[j++] = str[i];
}
else {
str[j++] = c2;
}
}
str[j] = '\0';
}
// Driver Code
int main()
{
// Given string
char str[] = "abacd";
char c1 = 'a';
char c2 = 'x';
// Function call
replaceCharacter(str, c1, c2);
// Print the string
cout << str;
return 0;
}
Java
public class Main {
// Function to replace all occurrences
// of character c1 with character c2
static void replaceCharacter(char[] str, char c1, char c2) {
int j = 0;
int n = str.length;
for (int i = 0; i < n; i++) {
if (str[i] != c1) {
str[j++] = str[i];
} else {
str[j++] = c2;
}
}
}
public static void main(String[] args) {
// Given string
char[] str = "abacd".toCharArray();
char c1 = 'a';
char c2 = 'x';
// Function call
replaceCharacter(str, c1, c2);
// Print the string
System.out.println(str);
}
}
Python3
# Function to replace all occurrences
# of character c1 with character c2
def replaceCharacter(str, c1, c2):
n = len(str)
res = ""
for i in range(n):
if str[i] != c1:
res += str[i]
else:
res += c2
return res
# Driver Code
if __name__ == '__main__':
# Given string
str = "abacd"
c1 = 'a'
c2 = 'x'
# Function call
str = replaceCharacter(str, c1, c2)
# Print the string
print(str)
C#
using System;
public class MainClass
{
// Function to replace all occurrences
// of character c1 with character c2
static void ReplaceCharacter(char[] str, char c1, char c2)
{
int j = 0;
int n = str.Length;
for (int i = 0; i < n; i++)
{
if (str[i] != c1)
{
str[j++] = str[i];
}
else
{
str[j++] = c2;
}
}
}
public static void Main(string[] args)
{
// Given string
char[] str = "abacd".ToCharArray();
char c1 = 'a';
char c2 = 'x';
// Function call
ReplaceCharacter(str, c1, c2);
// Print the string
Console.WriteLine(str);
}
}
JavaScript
// Function to replace all occurrences
// of character c1 with character c2
function replaceCharacter(str, c1, c2) {
let result = "";
for (let i = 0; i < str.length; i++) {
if (str[i] != c1) {
result += str[i];
} else {
result += c2;
}
}
return result;
}
// Given string
let str = "abacd";
let c1 = 'a';
let c2 = 'x';
// Function call
let newStr = replaceCharacter(str, c1, c2);
// Print the string
console.log(newStr);
Output-
xbxcd
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time.
Auxiliary Space: O(1), as we are not using any extra space.
Recursive Approach: The idea is to recursively traverse the given string and replace the character with value X with Y. Below are the steps:
- Get the string str, character X, and Y.
- Recursively Iterate from index 0 to string length.
- Base Case: If we reach the end of the string the exit from the function.
if(str[0]=='\0')
return ;
- Recursive Call: If the base case is not met, then check for the character at 0th index if it is X then replace that character with Y and recursively iterate for next character.
if(str[0]==X)
str[0] = Y
- Return Statement: At each recursive call(except the base case), return the recursive function for the next iteration.
return recursive_function(str + 1, X, Y)
Below is the recursive implementation:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to replace all occurrences
// of character c1 with character c2
void replaceCharacter(char input[],
char c1, char c2)
{
// Base Case
// If the string is empty
if (input[0] == '\0') {
return;
}
// If the character at starting
// of the given string is equal
// to c1, replace it with c2
if (input[0] == c1) {
input[0] = c2;
}
// Getting the answer from recursion
// for the smaller problem
return replaceCharacter(input + 1,
c1, c2);
}
// Driver Code
int main()
{
// Given string
char str[] = "abacd";
char c1 = 'a';
char c2 = 'x';
// Function call
replaceCharacter(str, c1, c2);
// Print the string
cout << str;
return 0;
}
Java
// Java program for the above approach
import java.util.*;
import java.io.*;
class GFG{
// Function to replace all occurrences
// of character c1 with character c2
static String replaceCharacter(String str,
char c1, char c2)
{
// Base Case
// If the string is empty
if (str.length() == 1)
{
return str;
}
char x=str.charAt(0);
// If the character at starting
// of the given string is equal
// to c1, replace it with c2
if (str.charAt(0) == c1)
{
x=c2;
str = c2+str.substring(1);
}
// Getting the answer from recursion
// for the smaller problem
return x+replaceCharacter(str.substring(1),
c1, c2);
}
// Driver Code
public static void main(String[] args)
{
// Given string
String str = "abacd";
char c1 = 'a';
char c2 = 'x';
// Function call
System.out.println(replaceCharacter(str, c1, c2));
}
}
// This code is contributed by cyrus18
Python3
# Python3 program for the above approach
# Function to replace all occurrences
# of character c1 with character c2
def replaceCharacter(input, c1, c2):
input = list(str)
# If the character at starting
# of the given string is equal
# to c1, replace it with c2
for i in range(0, len(str)):
if (input[i] == c1):
input[i] = c2;
# Print the string
print(input[i], end = "")
# Driver Code
# Given string
str = "abacd"
c1 = 'a'
c2 = 'x'
# Function call
replaceCharacter(str, c1, c2);
# This code is contributed by sanjoy_62
C#
// C# program for the above approach
using System;
class GFG{
// Function to replace all occurrences
// of character c1 with character c2
static void replaceCharacter(string str,
char c1, char c2)
{
char[] input = str.ToCharArray();
// If the character at starting
// of the given string is equal
// to c1, replace it with c2
for(int i = 0; i < str.Length; i++)
{
if (input[i] == c1)
{
input[i] = c2;
}
// Print the string
Console.Write(input[i]);
}
}
// Driver Code
public static void Main()
{
// Given string
string str = "abacd";
char c1 = 'a';
char c2 = 'x';
// Function call
replaceCharacter(str, c1, c2);
}
}
// This code is contributed by sanjoy_62
JavaScript
<script>
// javascript program for the above approach
// Function to replace all occurrences
// of character c1 with character c2
function replaceCharacter(str,c1, c2)
{
// Base Case
// If the string is empty
if (str.length == 1)
{
return str;
}
var x=str.charAt(0);
// If the character at starting
// of the given string is equal
// to c1, replace it with c2
if (str.charAt(0) == c1)
{
x=c2;
str = c2+str.substring(1);
}
// Getting the answer from recursion
// for the smaller problem
return x+replaceCharacter(str.substring(1),
c1, c2);
}
// Driver Code
//Given string
var str = "abacd";
var c1 = 'a';
var c2 = 'x';
// Function call
document.write(replaceCharacter(str, c1, c2));
// This code is contributed by 29AjayKumar
</script>
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time, where N is the length of the string.
Auxiliary Space: O(N), due to recursive stack space.
Similar Reads
How to Find and Replace All Occurrences of a Substring in a C++ String?
In C++, strings are sequences of characters that are used to represent textual data. In this article, we will learn how to find and replace all the occurrences of a particular substring in the given string. For Example, Input: str = "Lokesh is a good programmer, but Lokesh is still in the learning p
2 min read
Count of strings possible by replacing two consecutive same character with new character
Given string str. The task is to count the number of all different strings possible if two consecutive same characters of the string can be replaced by one different character. Examples Input: str = "abclll" Output: 3 Explanation: There can be 3 different string including the original string as show
8 min read
C++ Program to Replace a Character in a String
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input: grrksfoegrrks, c1 = e, c2 = r Output: geeksforgeeks Input: ratul, c1 = t, c2 = h Output: rahul Traverse through the string and check for the occurrences of c1 and c2. If c1 is found then replace it with c2 and
3 min read
How to Replace Text in a String Using Regex in C++?
Regular expressions or what we can call regex for short are sequences of symbols and characters that create a search pattern and help us to find specific patterns within a given text. In this article, we will learn how to replace text in a string using regex in C++. Example Input: str = "Hello, Worl
2 min read
Modify array of strings by replacing characters repeating in the same or remaining strings
Given an array of strings arr[] consisting of lowercase and uppercase characters only, the task is to modify the array by removing the characters from the strings which are repeating in the same string or any other string. Print the modified array. Examples: Input: arr[] = {"Geeks", "For", "Geeks"}O
6 min read
Remove odd frequency characters from the string
Given string str of size N, the task is to remove all the characters from the string that have odd frequencies. Examples: Input: str = "geeksforgeeks" Output: geeksgeeks The characters f, o, r have odd frequencies So, they are removed from the string. Input: str = "zzzxxweeerr" Output: xxrr Approach
9 min read
regex_replace in C++ | Replace the match of a string using regex_replace
std::regex_replace() is used to replace all matches in a string, Syntax: regex_replace(subject, regex_object, replace_text) Parameters: It accepts three parameters which are described below: Subject string as the first parameter. The regex object as the second parameter. The string with the replacem
3 min read
Remove first adjacent pairs of similar characters until possible
Given a string Str, the task is to remove first adjacent pairs of similar characters until we can. Note: Remove adjacent characters to get a new string and then again remove adjacent duplicates from the new string and keep repeating this process until all similar adjacent character pairs are removed
4 min read
C++ Program to Modify a string by performing given shift operations
Given a string S containing lowercase English alphabets, and a matrix shift[][] consisting of pairs of the form{direction, amount}, where the direction can be 0 (for left shift) or 1 (for right shift) and the amount is the number of indices by which the string S is required to be shifted. The task i
3 min read
How to Swap Two Strings Without Using Third String in C++?
In C++, a string is a sequence of characters. Swapping two strings typically involves using a third string as temporary storage. However, itâs possible to swap two strings without using a third string. In this article, we will learn how to do this in C++. Example Input: str1 = "Hello" str2 = "world"
2 min read