Replace two substrings (of a string) with each other
Last Updated :
15 Sep, 2022
Given 3 strings S, A and B. The task is to replace every sub-string of S equal to A with B and every sub-string of S equal to B with A. It is possible that two or more sub-strings matching A or B overlap. To avoid confusion about this situation, you should find the leftmost sub-string that matches A or B, replace it, and then continue with the rest of the string.
For example, when matching A = "aa" with S = "aaa", A[0, 1] will be given preference over A[1, 2].
Note that A and B will have the same length and A != B.
Examples:
Input: S = "aab", A = "aa", B = "bb"
Output: bbb
We match the first two characters with A and replacing it with B we get bbb.
Then we continue the algorithm starting at index 3 and we don't find any more matches.
Input: S = "aabbaabb", A = "aa", B = "bb"
Output: bbaabbaa
We replace all the occurrences of "aa" with "bb" and "bb" with "aa", so the resultant string is "bbaabbaa".
Approach: Go through every possible sub-string from S of length len(A). if any sub-string matches A or B then update the string as required and print the updated string in the end.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;
// Function to return the resultant string
string updateString(string S,
string A, string B)
{
int l = A.length();
// Iterate through all positions i
for (int i = 0; i + l <= S.length(); i++)
{
// Current sub-string of
// length = len(A) = len(B)
string curr = S.substr(i, i + l);
// If current sub-string gets
// equal to A or B
if (curr == A)
{
// Update S after replacing A
string new_string = "";
new_string += S.substr(0, i) + B +
S.substr(i + l, S.length());
S = new_string;
i += l - 1;
}
else if(curr == B)
{
// Update S after replacing B
string new_string = "";
new_string += S.substr(0, i) + A +
S.substr(i + l, S.length());
S = new_string;
i += l - 1;
}
else
{
//do nothing
}
}
// Return the updated string
return S;
}
// Driver code
int main()
{
string S = "aaxb";
string A = "aa";
string B = "bb";
cout << (updateString(S, A, B)) << endl;
}
// This code is contributed by
// Surendra_Gangwar
Java
// Java implementation of the approach
class GFG {
// Function to return the resultant string
static String updateString(String S, String A, String B)
{
int l = A.length();
// Iterate through all positions i
for (int i = 0; i + l <= S.length(); i++) {
// Current sub-string of length = len(A) = len(B)
String curr = S.substring(i, i + l);
// If current sub-string gets equal to A or B
if (curr.equals(A)) {
// Update S after replacing A
String new_string
= S.substring(0, i)
+ B + S.substring(i + l, S.length());
S = new_string;
i += l - 1;
}
else {
// Update S after replacing B
String new_string
= S.substring(0, i)
+ A + S.substring(i + l, S.length());
S = new_string;
i += l - 1;
}
}
// Return the updated string
return S;
}
// Driver code
public static void main(String[] args)
{
String S = "aab";
String A = "aa";
String B = "bb";
System.out.println(updateString(S, A, B));
}
}
Python3
# Python3 implementation of the approach
# Function to return the resultant string
def updateString(S, A, B):
l = len(A)
# Iterate through all positions i
i = 0
while i + l <= len(S):
# Current sub-string of
# length = len(A) = len(B)
curr = S[i:i+l]
# If current sub-string gets
# equal to A or B
if curr == A:
# Update S after replacing A
new_string = S[0:i] + B + S[i + l:len(S)]
S = new_string
i += l - 1
else:
# Update S after replacing B
new_string = S[0:i] + A + S[i + l:len(S)]
S = new_string
i += l - 1
i += 1
# Return the updated string
return S
# Driver code
if __name__ == "__main__":
S = "aab"
A = "aa"
B = "bb"
print(updateString(S, A, B))
# This code is contributed by Rituraj Jain
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the resultant string
static string updateString(string S, string A, string B)
{
int l = A.Length;
// Iterate through all positions i
for (int i = 0; i + l <= S.Length; i++)
{
// Current sub-string of length = len(A) = len(B)
string curr = S.Substring(i, l);
// If current sub-string gets equal to A or B
if (curr.Equals(A))
{
// Update S after replacing A
string new_string = S.Substring(0, i) +
B + S.Substring(i + l);
S = new_string;
i += l - 1;
}
else
{
// Update S after replacing B
string new_string = S.Substring(0, i) +
A + S.Substring(i + l);
S = new_string;
i += l - 1;
}
}
// Return the updated string
return S;
}
// Driver code
public static void Main()
{
string S = "aab";
string A = "aa";
string B = "bb";
Console.WriteLine(updateString(S, A, B));
}
}
// This code is contributed by Ryuga
PHP
<?php
// PHP implementation of the approach
// Function to return the resultant string
function updateString($S, $A, $B)
{
$l = strlen($A);
// Iterate through all positions i
for ($i = 0; $i + $l <= strlen($S); $i++)
{
// Current sub-string of length = len(A) = len(B)
$curr = substr($S, $i, $i + $l);
// If current sub-string gets equal to A or B
if (strcmp($curr, $A) == 0)
{
// Update S after replacing A
$new_string = substr($S, 0, $i) . $B .
substr($S, $i + $l, strlen($S));
$S = $new_string;
$i += $l - 1;
}
else
{
// Update S after replacing B
$new_string = substr($S, 0, $i) . $A .
substr($S, $i + $l, strlen($S));
$S = $new_string;
$i += $l - 1;
}
}
// Return the updated string
return $S;
}
// Driver code
$S = "aab";
$A = "aa";
$B = "bb";
echo(updateString($S, $A, $B));
// This code is contributed by Code_Mech.
JavaScript
<script>
// Javascript implementation of the approach
// Function to return the resultant string
function updateString(S, A, B)
{
let l = A.length;
// Iterate through all positions i
for(let i = 0; i + l <= S.length; i++)
{
// Current sub-string of length = len(A) = len(B)
let curr = S.substring(i, i + l);
// If current sub-string gets equal to A or B
if (curr == A)
{
// Update S after replacing A
let new_string = S.substring(0, i) +
B + S.substring(i + l);
S = new_string;
i += l - 1;
}
else
{
// Update S after replacing B
let new_string = S.substring(0, i) +
A + S.substring(i + l);
S = new_string;
i += l - 1;
}
}
// Return the updated string
return S;
}
// Driver code
let S = "aab";
let A = "aa";
let B = "bb";
document.write(updateString(S, A, B));
// This code is contributed by mukesh07
</script>
Complexity Analysis:
- Time Complexity: O(n*n), as substr function is being used inside the loop
- Auxiliary Space: O(n)
Similar Reads
replace() in Python to replace a substring replace() method in Python allows us to replace a specific part of a string with a new value. It returns a new string with the change without modifying the original one. We can also specify how many times the replacement should occur.For Example:Pythons = "hlo AB world" # Replace "AB" with "C" in `s
1 min read
Replace all occurrences of string AB with C without using extra space Given a string str that may contain one more occurrences of "AB". Replace all occurrences of "AB" with "C" in str. Examples: Input : str = "helloABworld"Output : str = "helloCworld"Input : str = "fghABsdfABysu"Output : str = "fghCsdfCysu"A simple solution is to find all occurrences of "AB". For ever
10 min read
Replace a character c1 with c2 and c2 with c1 in a string S 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
5 min read
Replace the given Strings starting from given indices Given a string S on which you need to perform Q replace operations.Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y. The rule is that if x starts at position i in the original string S, then \replace that occurrence of x with y. Note: All these ope
6 min read
Replace all occurrences of substring Given three strings s, s1, and s2 of lengths n, m, and k respectively, the task is to modify the string s by replacing all the substrings s1 with the string s2 in the string s.Examples:Input: s = "abababa", s1 = "aba", s2 = "a"Output: abaExplanation: Change the substrings s[0, 2] and s[4, 6] to the
11 min read
Enclose given Substrings of the String in parenthesis Given a string S and a list of strings subs[] that stores the substrings of S and all the substrings are present only once, the task is to enclose the substrings of S that exists in subs[] in parentheses. If substrings in subs[] overlap each other or are consecutive then merge them into one set of p
11 min read
Find the resultant String after replacing X with Y and removing Z Given a string str, the task is to replace all occurrences of the given X with given Y and also remove any occurrences of the given Z if present in it with no extra space Examples: Input: str = "batman", X = 'a', Y = 'd', Z = 'b' Output: ntdmdInput: str = "abba", X = 'a', Y = 'd', Z = 'b' Output: dd
7 min read
Check if String T can be made Substring of S by replacing given characters Given two strings S and T and a 2D array replace[][], where replace[i] = {oldChar, newChar} represents that the character oldChar of T is replaced with newChar. The task is to find if it is possible to make string T a substring of S by replacing characters according to the replace array. Note: Each
9 min read
String replace() method in Java with Examples The String replace() method returns a new string after replacing all the old characters/CharSequence with a given character/CharSequence. Example:Return a new string where all " o" characters are replaced with "p" character: Java // Java program to demonstrate // the replace() method public class Ma
4 min read
Minimum characters to be replaced to remove the given substring Given two strings str1 and str2. The task is to find the minimum number of characters to be replaced by $ in string str1 such that str1 does not contain string str2 as any substring. Examples: Input: str1 = "intellect", str2 = "tell" Output: 1 4th character of string "str1" can be replaced by $ such
7 min read