How to replace a substring of a string
Last Updated :
26 Apr, 2023
Given three strings S, S1, and S2 consisting of N, M, and K characters 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: aba
Explanation:
Change the substrings S[0, 2] and S[4, 6](= S1) to the string S2(= “a”) modifies the string S to “aba”. Therefore, print “aba”.
Input: S = “geeksforgeeks”, S1 = “eek”, S2 = “ok”
Output: goksforgoks
Naive Approach: The simplest approach to solve the given problem is to traverse the string S and when any string S1 is found as a substring in the string S then replace it by S2. Follow the steps below to solve this problem:
- Initialize a string ans to store the resultant string after replacing all the occurrences of the substring S1 to S2 in the string S.
- Iterate over the characters of the string S using variable i and perform the following steps:
- If the prefix substring of the string S is equal to S1 from the index i, then add the string S2 in the string ans.
- Otherwise, add the current character to the string ans.
- After completing the above steps, print the string ans as the result.
Below is the implementation of the above approach:
C
#include <stdio.h>
#include <string.h>
void modifyString( char * s, char * s1, char * s2)
{
char ans[1000] = { 0 };
int ans_idx = 0;
for ( int i = 0; i < strlen (s); i++) {
int k = 0;
if (s[i] == s1[k] && i + strlen (s1) <= strlen (s)) {
int j;
for (j = i; j < i + strlen (s1); j++) {
if (s[j] != s1[k]) {
break ;
}
else {
k = k + 1;
}
}
if (j == i + strlen (s1)) {
for ( int l = 0; l < strlen (s2); l++) {
ans[ans_idx++] = s2[l];
}
i = j - 1;
}
else {
ans[ans_idx++] = s[i];
}
}
else {
ans[ans_idx++] = s[i];
}
}
printf ( "%s" , ans);
}
int main()
{
char S[] = "geeksforgeeks" ;
char S1[] = "eek" ;
char S2[] = "ok" ;
modifyString(S, S1, S2);
return 0;
}
|
C++
#include <bits/stdc++.h>
using namespace std;
void modifyString(string& s, string& s1,
string& s2)
{
string ans = "" ;
for ( int i = 0; i < s.length(); i++) {
int k = 0;
if (s[i] == s1[k]
&& i + s1.length()
<= s.length()) {
int j;
for (j = i; j < i + s1.length(); j++) {
if (s[j] != s1[k]) {
break ;
}
else {
k = k + 1;
}
}
if (j == i + s1.length()) {
ans.append(s2);
i = j - 1;
}
else {
ans.push_back(s[i]);
}
}
else {
ans.push_back(s[i]);
}
}
cout << ans;
}
int main()
{
string S = "geeksforgeeks" ;
string S1 = "eek" ;
string S2 = "ok" ;
modifyString(S, S1, S2);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void modifyString(String s, String s1, String s2)
{
String ans = "" ;
for ( int i = 0 ; i < s.length(); i++) {
int k = 0 ;
if (s.charAt(i) == s1.charAt(k)
&& i + s1.length() <= s.length()) {
int j;
for (j = i; j < i + s1.length(); j++) {
if (s.charAt(j) != s1.charAt(k)) {
break ;
}
else {
k = k + 1 ;
}
}
if (j == i + s1.length()) {
ans += (s2);
i = j - 1 ;
}
else {
ans += (s.charAt(i));
}
}
else {
ans += (s.charAt(i));
}
}
System.out.print(ans);
}
public static void main(String[] args)
{
String S = "geeksforgeeks" ;
String S1 = "eek" ;
String S2 = "ok" ;
modifyString(S, S1, S2);
}
}
|
Python3
def modifyString(s, s1, s2):
ans = ""
i = 0
while i < len (s):
k = 0
if s[i] = = s1[k] and i + len (s1) < = len (s):
j = i
while j < i + len (s1) and s[j] = = s1[k]:
k + = 1
j + = 1
if j = = i + len (s1):
ans + = s2
i = j - 1
else :
ans + = s[i]
else :
ans + = s[i]
i + = 1
print (ans)
S = "geeksforgeeks"
S1 = "eek"
S2 = "ok"
modifyString(S, S1, S2)
|
C#
using System;
public class GFG {
static void modifyString(String s, String s1, String s2)
{
String ans = "" ;
for ( int i = 0; i < s.Length; i++) {
int k = 0;
if (s[i] == s1[k]
&& i + s1.Length <= s.Length) {
int j;
for (j = i; j < i + s1.Length; j++) {
if (s[j] != s1[k]) {
break ;
}
else {
k = k + 1;
}
}
if (j == i + s1.Length) {
ans += (s2);
i = j - 1;
}
else {
ans += (s[i]);
}
}
else {
ans += (s[i]);
}
}
Console.Write(ans);
}
public static void Main(String[] args)
{
String S = "geeksforgeeks" ;
String S1 = "eek" ;
String S2 = "ok" ;
modifyString(S, S1, S2);
}
}
|
Javascript
<script>
function modifylet(s, s1,
s2)
{
let ans = "" ;
for (let i = 0; i < s.length; i++) {
let k = 0;
if (s[i] == s1[k]
&& i + s1.length
<= s.length) {
let j;
for (j = i; j < i + s1.length; j++) {
if (s[j] != s1[k]) {
break ;
}
else {
k = k + 1;
}
}
if (j == i + s1.length) {
ans = ans + s2;
i = j - 1;
}
else {
ans = ans + s[i];
}
}
else {
ans = ans + s[i];
}
}
document.write(ans);
}
let S = "geeksforgeeks" ;
let S1 = "eek" ;
let S2 = "ok" ;
modifylet(S, S1, S2);
</script>
|
Time Complexity: O(N*M)
Auxiliary Space: O(N)
Efficient Approach: The above approach can also be optimized by creating the longest proper prefix and suffix array for the string S1 and then perform the KMP Algorithm to find the occurrences of the string S1 in the string S. Follow the steps below to solve this problem:
- Create a vector, say lps[] that stores the longest proper prefix and suffix for each character and fill this vector using the KMP algorithm for the string S1.
- Initialize two variables say, i and j as 0 to store the position of current character in s and s1 respectively.
- Initialize a vector found to store all the starting indexes from which string S1 occurs in S.
- Iterate over the characters of the string S using variable i and perform the following steps:
- If S[i] is equal to S1[j], then increment i and j by 1.
- If j is equal to the length of s1, then add the value (i – j) to the vector found and update j as lps[j – 1].
- Otherwise, if the value of S[i] is not equal to S1[j], then if j is equal to 0, then increment the value of i by 1. Otherwise, update j as lps[j – 1].
- Initialize a variable say, prev as 0 to store the last changed index and an empty string ans to store the resultant string after replacing all the initial appearances of s1 by s2 in s.
- Traverse the vector found[] and if the value of found[i] is greater than prev, then add the string S2 in place of S1 in ans.
- After completing the above steps, print the string ans as the result.
Below is the implementation of the above approach:
C
#include <stdio.h>
#include <string.h>
void computeLPS( char * s1, int * lps)
{
int len = 0;
lps[0] = 0;
int i = 1;
while (i < strlen (s1)) {
if (s1[i] == s1[len]) {
len = len + 1;
lps[i] = len;
i = i + 1;
}
else {
if (len == 0) {
lps[i] = 0;
i = i + 1;
}
else
len = lps[len - 1];
}
}
}
void modifyString( char * s, char * s1, char * s2)
{
int n = strlen (s);
int m = strlen (s1);
int lps[m];
computeLPS(s1, lps);
int i = 0;
int j = 0;
int found[n / m + 1];
int k = 0;
while (i < n) {
if (s[i] == s1[j]) {
i = i + 1;
j = j + 1;
}
if (j == m) {
found[k++] = i - j;
j = lps[j - 1];
}
else if (i < n && s1[j] != s[i]) {
if (j == 0)
i = i + 1;
else
j = lps[j - 1];
}
}
char ans[n + k * ( strlen (s2) - m) + 1];
int prev = 0;
int ans_len = 0;
for ( int l = 0; l < k; l++) {
if (found[l] < prev)
continue ;
strncpy (ans + ans_len, s + prev, found[l] - prev);
ans_len += found[l] - prev;
strncpy (ans + ans_len, s2, strlen (s2));
ans_len += strlen (s2);
prev = found[l] + m;
}
strncpy (ans + ans_len, s + prev, n - prev);
ans_len += n - prev;
ans[ans_len] = '\0' ;
printf ( "%s\n" , ans);
}
int main()
{
char S[] = "geeksforgeeks" ;
char S1[] = "eek" ;
char S2[] = "ok" ;
modifyString(S, S1, S2);
return 0;
}
|
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > computeLPS(string& s1)
{
vector< int > lps(s1.length());
int len = 0;
lps[0] = 0;
int i = 1;
while (i < s1.length()) {
if (s1[i] == s1[len]) {
len = len + 1;
lps[i] = len;
i = i + 1;
}
else {
if (len == 0) {
lps[i] = 0;
i = i + 1;
}
else
len = lps[len - 1];
}
}
return lps;
}
void modifyString(string& s, string& s1,
string& s2)
{
vector< int > lps = computeLPS(s1);
int i = 0;
int j = 0;
vector< int > found;
while (i < s.length()) {
if (s[i] == s1[j]) {
i = i + 1;
j = j + 1;
}
if (j == s1.length()) {
found.push_back(i - j);
j = lps[j - 1];
}
else if (i < s.length()
&& s1[j] != s[i]) {
if (j == 0)
i = i + 1;
else
j = lps[j - 1];
}
}
string ans = "" ;
int prev = 0;
for ( int k = 0; k < found.size(); k++) {
if (found[k] < prev)
continue ;
ans.append(s.substr(prev, found[k] - prev));
ans.append(s2);
prev = found[k] + s1.size();
}
ans.append(s.substr(prev,
s.length() - prev));
cout << ans << endl;
}
int main()
{
string S = "geeksforgeeks" ;
string S1 = "eek" ;
string S2 = "ok" ;
modifyString(S, S1, S2);
return 0;
}
|
Java
import java.util.ArrayList;
class Replace
{
static int [] computeLPS(String s1)
{
int [] lps = new int [s1.length()];
int len = 0 ;
lps[ 0 ] = 0 ;
int i = 1 ;
while (i < s1.length())
{
if (s1.charAt(i) == s1.charAt(len))
{
len = len + 1 ;
lps[i] = len;
i = i + 1 ;
}
else
{
if (len == 0 )
{
lps[i] = 0 ;
i = i + 1 ;
}
else
len = lps[len - 1 ];
}
}
return lps;
}
static void modifyString(String s, String s1,
String s2)
{
int [] lps = computeLPS(s1);
int i = 0 ;
int j = 0 ;
ArrayList<Integer> found = new ArrayList<>();
while (i < s.length())
{
if (s.charAt(i) == s1.charAt(j))
{
i = i + 1 ;
j = j + 1 ;
}
if (j == s1.length())
{
found.add(i - j);
j = lps[j - 1 ];
}
else if (i < s.length()
&& s1.charAt(j) != s.charAt(i))
{
if (j == 0 )
i = i + 1 ;
else
j = lps[j - 1 ];
}
}
String ans = "" ;
int prev = 0 ;
for ( int k = 0 ; k < found.size(); k++)
{
if (found.get(k) < prev)
continue ;
ans += s.substring(prev, found.get(k));
ans += s2;
prev = found.get(k) + s1.length();
}
ans += s.substring(prev,
s.length());
System.out.println(ans);
}
public static void main (String[] args)
{
String S = "geeksforgeeks" ;
String S1 = "eek" ;
String S2 = "ok" ;
modifyString(S, S1, S2);
}
}
|
Python3
def computeLPS(s1):
lps = [ 0 ] * len (s1)
length = 0
lps[ 0 ] = 0
i = 1
while i < len (s1):
if s1[i] = = s1[length]:
length + = 1
lps[i] = length
i + = 1
else :
if length = = 0 :
lps[i] = 0
i + = 1
else :
length = lps[length - 1 ]
return lps
def modifyString(s, s1, s2):
lps = computeLPS(s1)
i = j = 0
found = []
while i < len (s):
if s[i] = = s1[j]:
i + = 1
j + = 1
if j = = len (s1):
found.append(i - j)
j = lps[j - 1 ]
elif i < len (s) and s1[j] ! = s[i]:
if j = = 0 :
i + = 1
else :
j = lps[j - 1 ]
ans = ""
prev = 0
for k in range ( len (found)):
if found[k] < prev:
continue
ans + = s[prev:found[k]]
ans + = s2
prev = found[k] + len (s1)
ans + = s[prev:]
print (ans)
S = "geeksforgeeks"
S1 = "eek"
S2 = "ok"
modifyString(S, S1, S2)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static List< int > ComputeLPS( string s1)
{
List< int > lps = new List< int >(s1.Length);
int len = 0;
lps.Add(0);
int i = 1;
while (i < s1.Length) {
if (s1[i] == s1[len]) {
len = len + 1;
lps.Add(len);
i = i + 1;
}
else {
if (len == 0) {
lps.Add(0);
i = i + 1;
}
else
len = lps[len - 1];
}
}
return lps;
}
static void ModifyString( string s, string s1, string s2)
{
List< int > lps = ComputeLPS(s1);
int i = 0;
int j = 0;
List< int > found = new List< int >();
while (i < s.Length) {
if (s[i] == s1[j]) {
i = i + 1;
j = j + 1;
}
if (j == s1.Length) {
found.Add(i - j);
j = lps[j - 1];
}
else if (i < s.Length && s1[j] != s[i]) {
if (j == 0)
i = i + 1;
else
j = lps[j - 1];
}
}
string ans = "" ;
int prev = 0;
for ( int k = 0; k < found.Count; k++) {
if (found[k] < prev)
continue ;
ans += s.Substring(prev, found[k] - prev);
ans += s2;
prev = found[k] + s1.Length;
}
ans += s.Substring(prev, s.Length - prev);
Console.WriteLine(ans);
}
static void Main()
{
string S = "geeksforgeeks" ;
string S1 = "eek" ;
string S2 = "ok" ;
ModifyString(S, S1, S2);
}
}
|
Javascript
function computeLPS(s1)
{
let lps = new Array(s1.length).fill(0);
let len = 0;
lps[0] = 0;
let i = 1;
while (i < s1.length) {
if (s1[i] == s1[len]) {
len = len + 1;
lps[i] = len;
i = i + 1;
}
else {
if (len == 0) {
lps[i] = 0;
i = i + 1;
}
else
len = lps[len - 1];
}
}
return lps;
}
function modifyString(s, s1, s2)
{
let lps = computeLPS(s1);
let i = 0;
let j = 0;
let found = [];
while (i < s.length) {
if (s[i] == s1[j]) {
i = i + 1;
j = j + 1;
}
if (j == s1.length) {
found.push(i - j);
j = lps[j - 1];
}
else if (i < s.length
&& s1[j] != s[i]) {
if (j == 0)
i = i + 1;
else
j = lps[j - 1];
}
}
let ans = "" ;
let prev = 0;
for (let k = 0; k < found.length; k++) {
if (found[k] < prev)
continue ;
ans = ans + s.substring(prev, found[k]);
ans = ans + s2;
prev = found[k] + s1.length;
}
ans = ans + s.substring(prev,
s.length);
console.log(ans);
}
let S = "geeksforgeeks" ;
let S1 = "eek" ;
let S2 = "ok" ;
modifyString(S, S1, S2);
|
Time Complexity: O(N + M)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...