Replace all occurrences of substring
Last Updated :
11 May, 2025
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: aba
Explanation: Change the substrings s[0, 2] and s[4, 6] to the string s2 modifies the string s to "aba".
Input: s = "geeksforgeeks", s1 = "eek", s2 = "ok"
Output: goksforgoks
Explanation: Change the substrings s[1, 3] and s[9, 11] to the string
[Naive Approach] Using Nested Loop – O(n*m) Time and O(n) Space
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.
C++
#include <iostream>
#include <string>
using namespace std;
string replaceSubstr(string s, string s1, string s2)
{
string ans = "";
int n = s.length(), m = s1.length();
for (int i = 0; i < n; i++)
{
if (i + m <= n && s.substr(i, m) == s1)
{
ans += s2;
// Skip the characters of s1
i += m - 1;
}
else
{
ans += s[i];
}
}
return ans;
}
int main()
{
string s = "abababa", s1 = "aba", s2 = "a";
cout << replaceSubstr(s, s1, s2) << endl;
return 0;
}
Java
public class GFG {
public static String replaceSubstr(String s, String s1,
String s2)
{
StringBuilder ans = new StringBuilder();
int n = s.length(), m = s1.length();
for (int i = 0; i < n; i++) {
if (i + m <= n
&& s.substring(i, i + m).equals(s1)) {
ans.append(s2);
// Skip the characters of s1
i += m - 1;
}
else {
ans.append(s.charAt(i));
}
}
return ans.toString();
}
public static void main(String[] args)
{
String s = "abababa", s1 = "aba", s2 = "a";
System.out.println(replaceSubstr(s, s1, s2));
}
}
Python
def replaceSubstr(s, s1, s2):
ans = ""
n, m = len(s), len(s1)
i = 0
while i < n:
if i + m <= n and s[i:i + m] == s1:
ans += s2
# Skip the characters of s1
i += m - 1
else:
ans += s[i]
i += 1
return ans
s = "abababa"
s1 = "aba"
s2 = "a"
print(replaceSubstr(s, s1, s2))
C#
using System;
class GFG {
static string ReplaceSubstr(string s, string s1,
string s2)
{
string ans = "";
int n = s.Length, m = s1.Length;
for (int i = 0; i < n; i++) {
if (i + m <= n && s.Substring(i, m) == s1) {
ans += s2;
// Skip the characters of s1
i += m - 1;
}
else {
ans += s[i];
}
}
return ans;
}
static void Main()
{
string s = "abababa", s1 = "aba", s2 = "a";
Console.WriteLine(ReplaceSubstr(s, s1, s2));
}
}
JavaScript
function replaceSubstr(s, s1, s2)
{
let ans = "";
let n = s.length, m = s1.length;
for (let i = 0; i < n; i++) {
if (i + m <= n && s.substring(i, i + m) === s1) {
ans += s2;
// Skip the characters of s1
i += m - 1;
}
else {
ans += s[i];
}
}
return ans;
}
let s = "abababa";
let s1 = "aba";
let s2 = "a";
console.log(replaceSubstr(s, s1, s2));
[Expected Approach] Using KMP Algorithm– O(n+m) Time and O(m) Space
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.
Algorithm:
- Create a array lps[] that stores the longest proper prefix and suffix for each character and fill this array 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 array 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 array 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 array 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.
C++
#include <iostream>
#include <vector>
using namespace std;
// Compute the LPS (Longest Prefix Suffix) array
vector<int> computeLPS(string pattern) {
int m = pattern.length();
vector<int> lps(m, 0);
int len = 0;
for (int i = 1; i < m; ) {
if (pattern[i] == pattern[len]) {
lps[i++] = ++len;
} else {
if (len != 0) len = lps[len - 1];
else lps[i++] = 0;
}
}
return lps;
}
// Function to perform the replace using KMP
string replaceSubstr(string s, string s1, string s2) {
int n = s.length();
int m = s1.length();
vector<int> lps = computeLPS(s1);
string ans;
int i = 0, j = 0;
while (i < n) {
if (s[i] == s1[j]) {
i++, j++;
if (j == m) {
// Match found; replace
ans += s2;
j = 0; // Reset pattern pointer for next match
}
} else {
if (j != 0) j = lps[j - 1];
else {
ans += s[i++];
}
}
}
// Add remaining unmatched characters
if (j != 0) ans += s.substr(i - j, j);
return ans;
}
int main()
{
string s = "abababa", s1 = "aba", s2 = "a";
cout << replaceSubstr(s, s1, s2) << endl;
return 0;
}
Java
import java.util.*;
public class GfG{
// Compute the LPS (Longest Prefix Suffix) array
public static int[] computeLPS(String pattern) {
int m = pattern.length();
int[] lps = new int[m];
int len = 0;
for (int i = 1; i < m; ) {
if (pattern.charAt(i) == pattern.charAt(len)) {
lps[i++] = ++len;
} else {
if (len != 0) len = lps[len - 1];
else lps[i++] = 0;
}
}
return lps;
}
// Function to perform the replace using KMP
public static String replaceSubstr(String s, String s1, String s2) {
int[] lps = computeLPS(s1);
StringBuilder ans = new StringBuilder();
int i = 0, j = 0;
int n = s.length(), m = s1.length();
while (i < n) {
if (s.charAt(i) == s1.charAt(j)) {
i++; j++;
if (j == m) {
// Match found; replace
ans.append(s2);
j = 0; // Reset pattern pointer for next match
}
} else {
if (j != 0) j = lps[j - 1];
else ans.append(s.charAt(i++));
}
}
// Add remaining unmatched characters
if (j != 0) ans.append(s.substring(i - j, i));
return ans.toString();
}
public static void main(String[] args) {
String s = "abababa", s1 = "aba", s2 = "a";
System.out.println(replaceSubstr(s, s1, s2));
}
}
Python
# Compute the LPS (Longest Prefix Suffix) array
def compute_lps(pattern):
m = len(pattern)
lps = [0] * m
length = 0
i = 1
while i < m:
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
return lps
# Function to perform the replace using KMP
def replaceSubstr(s, s1, s2):
n, m = len(s), len(s1)
lps = compute_lps(s1)
ans = []
i = j = 0
while i < n:
if s[i] == s1[j]:
i += 1
j += 1
if j == m:
# Match found; replace
ans.append(s2)
# Reset pattern pointer for next match
j = 0
else:
if j != 0:
j = lps[j - 1]
else:
ans.append(s[i])
i += 1
# Add remaining unmatched characters
if j != 0:
ans.append(s[i - j:i])
return ''.join(ans)
if __name__ == '__main__':
s = "abababa"
s1 = "aba"
s2 = "a";
print(replaceSubstr(s, s1, s2))
C#
using System;
using System.Text;
class GfG{
// Compute the LPS (Longest Prefix Suffix) array
static int[] ComputeLPS(string pattern) {
int m = pattern.Length;
int[] lps = new int[m];
int len = 0;
int i = 1;
while (i < m) {
if (pattern[i] == pattern[len]) {
lps[i++] = ++len;
} else {
if (len != 0) len = lps[len - 1];
else lps[i++] = 0;
}
}
return lps;
}
// Function to perform the replace using KMP
static string replaceSubstr(string s, string s1, string s2) {
int[] lps = ComputeLPS(s1);
StringBuilder ans = new StringBuilder();
int i = 0, j = 0;
int n = s.Length, m = s1.Length;
while (i < n) {
if (s[i] == s1[j]) {
i++; j++;
if (j == m) {
// Match found; replace
ans.Append(s2);
j = 0; // Reset pattern pointer for next match
}
} else {
if (j != 0) j = lps[j - 1];
else ans.Append(s[i++]);
}
}
// Add remaining unmatched characters
if (j != 0) ans.Append(s.Substring(i - j, j));
return ans.ToString();
}
static void Main() {
string s = "abababa", s1 = "aba", s2 = "a";
Console.WriteLine(replaceSubstr(s, s1, s2));
}
}
JavaScript
// Compute the LPS (Longest Prefix Suffix) array
function computeLPS(pattern) {
const m = pattern.length;
const lps = Array(m).fill(0);
let len = 0;
for (let i = 1; i < m;) {
if (pattern[i] === pattern[len]) {
lps[i++] = ++len;
} else {
if (len !== 0) len = lps[len - 1];
else lps[i++] = 0;
}
}
return lps;
}
// Function to perform the replace using KMP
function replaceSubstr(s, s1, s2) {
const lps = computeLPS(s1);
let ans = "";
let i = 0, j = 0;
const n = s.length, m = s1.length;
while (i < n) {
if (s[i] === s1[j]) {
i++; j++;
if (j === m) {
// Match found; replace
ans += s2;
j = 0; // Reset pattern pointer for next match
}
} else {
if (j !== 0) j = lps[j - 1];
else ans += s[i++];
}
}
// Add remaining unmatched characters
if (j !== 0) ans += s.slice(i - j, i);
return ans;
}
// Driver Code
const s = "abababa", s1 = "aba", s2 = "a";
console.log(replaceSubstr(s, s1, s2));
Time Complexity: The time complexity is O(n + m), where n
is the length of string s
and m
is the length of string s1
.
The LPS function runs in O(m) time to compute the prefix-suffix array, and the main loop processes string s
in O(n) time.
Auxiliary Space: The LPS array requires O(m) space, where m
is the length of s1
, so the overall space complexity is O(m).
Using Library Methods - O(n*m) time and O(n) space
C++
#include <iostream>
#include <string>
using namespace std;
// Function to perform the replace
string replaceSubstr(string s, const string& s1, const string& s2) {
size_t pos = 0;
// Replace all non-overlapping occurrences of s1 with s2
while ((pos = s.find(s1, pos)) != string::npos) {
s.replace(pos, s1.length(), s2);
// Move past the replaced part
pos += s2.length();
}
return s;
}
int main() {
string s = "abababa", s1 = "aba", s2 = "a";
cout << replaceSubstr(s, s1, s2) << endl;
return 0;
}
Java
public class GfG {
// Function to perform the replace
static String replaceSubstr(String s, String s1,
String s2) {
// Replace all non-overlapping occurrences
return s.replace(s1, s2);
}
public static void main(String[] args) {
String s = "abababa", s1 = "aba", s2 = "a";
System.out.println(replaceSubstr(s, s1, s2));
}
}
Python
# Function to perform the replace
def replaceSubstr(s, s1, s2):
# Replace all non-overlapping occurrences
return s.replace(s1, s2)
if __name__ == "__main__":
s = "abababa"
s1 = "aba"
s2 = "a"
print(replaceSubstr(s, s1, s2))
C#
using System;
class GfG{
// Function to perform the replace
static string replaceSubstr(string s, string s1, string s2) {
// Replace all non-overlapping occurrences
return s.Replace(s1, s2);
}
static void Main() {
string s = "abababa", s1 = "aba", s2 = "a";
Console.WriteLine(replaceSubstr(s, s1, s2));
}
}
JavaScript
// Function to perform the replace
function replaceSubstr(s, s1, s2) {
// Replace all non-overlapping occurrences
return s.replaceAll(s1, s2); // ES2021+
// Or for older environments:
// return s.split(s1).join(s2);
}
// Driver Code
const s = "abababa", s1 = "aba", s2 = "a";
console.log(replaceSubstr(s, s1, s2));
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
In-place replace multiple occurrences of a pattern Given a string and a pattern, replace multiple occurrences of a pattern by character âXâ. The conversion should be in-place and the solution should replace multiple consecutive (and non-overlapping) occurrences of a pattern by a single âXâ. String â GeeksForGeeks Pattern â Geeks Output: XforX String
13 min read
All substrings of a given String Given a string s, containing lowercase alphabetical characters. The task is to print all non-empty substrings of the given string.Examples : Input : s = "abc"Output : "a", "ab", "abc", "b", "bc", "c"Input : s = "ab"Output : "a", "ab", "b"Input : s = "a"Output : "a"[Expected Approach] - Using Iterati
8 min read
Maximize cost of removing all occurrences of substrings "ab" and "ba" Given a string S and integers P and Q, which denotes the cost of removal of substrings "ab" and "ba" respectively from S, the task is to find the maximum cost of removing all occurrences of substrings "ab" and "ba". Examples: Input: S = "cbbaabbaab", P = 6, Q = 4Output: 22Explanation:Removing substr
10 min read
Queries for frequencies of characters in substrings Given a string s and Q number of queries. Each query Q consists of l and r and a character c. Find the frequency of character c in substring l to r. Examples: Input : s = geeksforgeeks 4 0 5 e 2 6 f 4 7 m 0 12 e Output : 2 1 0 4 Substring from 0 to 5 is geeksf. Here e occurs 2 times. Input : s = app
6 min read
Remove all occurrences of string t in string s using KMP Algorithm Given two strings s and t, the task is to remove all occurrences of t in s and return the modified string s, and you have to use the KMP algorithm to solve this. Examples: Input: s = "abcdefgabcabcabdefghabc", t = "abc"Output: "defgdefgh" Input: s = "aaabbbccc", t = "bbb"Output: "aaaccc" Approach: T
8 min read
Replace two substrings (of a string) with each other 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
7 min read
Remove last occurrence of a word from a given sentence string Given two strings S and W of sizes N and M respectively, the task is to remove the last occurrence of W from S. If there is no occurrence of W in S, print S as it is. Examples: Input: S = âThis is GeeksForGeeksâ, W="Geeks"Output: This is GeeksForExplanation:The last occurrence of âGeeksâ in the stri
11 min read
Frequency of a Substring in a String Given an input string and a pattern, the task is to find the frequency of occurrences of the string pattern in a given string. Examples: Input: pattern = "man", string = "dhimanman"Output: 2 Input: pattern = "nn", string = "Banana"Output: 0 Input: pattern = "aa", string = "aaaaa"Output : 4 Recommend
14 min read