In-place replace multiple occurrences of a pattern
Last Updated :
25 Apr, 2023
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 – GeeksGeeks
Pattern – Geeks
Output: X
String – aaaa
Pattern – aa
Output: X
String – aaaaa
Pattern – aa
Output: Xa
The idea is to maintain two index i and j for in-place replacement. Index i always points to next character in the output string. Index j traverses the string and searches for one or more pattern match. If a match is found, we put character ‘X’ at index i and increment index i by 1 and index j by length of the pattern. Index i is increment only once if we find multiple consecutive occurrences of the pattern. If the pattern is not found, we copy current character at index j to index i and increment both i and j by 1. Since pattern length is always more than equal to 1 and replacement is only 1 character long, we would never overwrite unprocessed characters i.e j >= i is invariant.
Implementation:
C++
// C++ program to in-place replace multiple
// occurrences of a pattern by character ‘X’
#include <bits/stdc++.h>
using namespace std;
// returns true if pattern is prefix of str
bool compare(char* str, char* pattern)
{
for (int i = 0; pattern[i]; i++)
if (str[i] != pattern[i])
return false;
return true;
}
// Function to in-place replace multiple
// occurrences of a pattern by character ‘X’
void replacePattern(char* str, char* pattern)
{
// If pattern is null or empty string,
// nothing needs to be done
if (pattern == NULL)
return;
int len = strlen(pattern);
if (len == 0)
return;
int i = 0, j = 0;
int count;
// for each character
while (str[j]) {
count = 0;
// compare str[j..j+len] with pattern
while (compare(str + j, pattern)) {
// increment j by length of pattern
j = j + len;
count++;
}
// If single or multiple occurrences of pattern
// is found, replace it by character 'X'
if (count > 0)
str[i++] = 'X';
// copy character at current position j
// to position i and increment i and j
if (str[j])
str[i++] = str[j++];
}
// add a null character to terminate string
str[i] = '\0';
}
// Driver code
int main()
{
char str[] = "GeeksforGeeks";
char pattern[] = "Geeks";
replacePattern(str, pattern);
cout << str;
return 0;
}
Java
// Java equivalent
// Java program to in-place replace multiple
// occurrences of a pattern by character ‘X’
public class ReplaceOccurrences
{
// returns true if pattern is prefix of str
public static boolean compare(String str, String pattern)
{
for (int i = 0; i<pattern.length(); i++)
if (str.charAt(i) != pattern.charAt(i))
return false;
return true;
}
// Function to in-place replace multiple
// occurrences of a pattern by character ‘X’
public static String replacePattern(String str, String pattern)
{
// If pattern is null or empty string,
// nothing needs to be done
if (pattern == "")
return str;
int len = pattern.length();
if (len == 0)
return str;
int i = 0, j = 0;
int count;
// for each character
while (j<str.length())
{
count = 0;
// compare str[j..j+len] with pattern
if (j + len <= str.length() && compare(str.substring(j,j+len), pattern))
{
// increment j by length of pattern
j = j + len;
count++;
}
// If single or multiple occurrences of pattern
// is found, replace it by character 'X'
if (count > 0)
{
String firstPart = str.substring(0,i);
String lastPart = str.substring(i+1);
str = firstPart + 'X' + lastPart;
i++;
}
// copy character at current position j
// to position i and increment i and j
if (j<str.length())
{
String firstPart = str.substring(0,i);
String lastPart = str.substring(i+1);
str = firstPart + str.charAt(j) + lastPart;
i++; j++;
}
}
// add a null character to terminate string
String firstPart = str.substring(0,i);
str = firstPart;
return str;
}
// Driver code
public static void main(String[] args)
{
String str = "GeeksforGeeks";
String pattern = "Geeks";
str = replacePattern(str, pattern);
System.out.println(str);
}
}
Python3
# Python3 program to in-place replace multiple
# occurrences of a pattern by character ‘X’
# returns true if pattern is prefix of Str
def compare(Str, pattern):
if(len(Str) != len(pattern)):
return False
for i in range(len(pattern)):
if (Str[i] != pattern[i]):
return False
return True
# Function to in-place replace multiple
# occurrences of a pattern by character ‘X’
def replacePattern(Str,pattern):
# If pattern is null or empty String,
# nothing needs to be done
if (pattern == ""):
return
Len = len(pattern)
if (Len == 0):
return
i, j = 0, 0
# for each character
while (j < len(Str)):
count = 0
# compare Str[j..j+len] with pattern
while (compare(Str[j:j+Len], pattern)):
# increment j by length of pattern
j = j + Len
count += 1
# If single or multiple occurrences of pattern
# is found, replace it by character 'X'
if (count > 0):
Str = Str[0:i] + 'X' + Str[i+1:]
i += 1
# copy character at current position j
# to position i and increment i and j
if (j<len(Str)):
Str = Str[0:i] + Str[j] + Str[i+1:]
i += 1
j += 1
# add a null character to terminate String
Str = Str[0:i]
return Str
# Driver code
Str = "GeeksforGeeks"
pattern = "Geeks"
Str = replacePattern(Str, pattern)
print(Str)
# This code is contributed by shinjanpatra
C#
// C# program for the above approach
using System;
public class Program
{
// returns true if pattern is prefix of str
static bool Compare(string str, string pattern)
{
for (int i = 0; i < pattern.Length; i++)
if (str[i] != pattern[i])
return false;
return true;
}
// Function to in-place replace multiple
// occurrences of a pattern by character ‘X’
static void ReplacePattern(char[] str, string pattern)
{
// If pattern is null or empty string,
// nothing needs to be done
if (pattern == null)
return;
int len = pattern.Length;
if (len == 0)
return;
int i = 0, j = 0;
int count;
// for each character
while (j < str.Length) {
count = 0;
// compare str[j..j+len] with pattern
while (j + len <= str.Length && Compare(new string(str, j, len), pattern)) {
// increment j by length of pattern
j = j + len;
count++;
}
// If single or multiple occurrences of pattern
// is found, replace it by character 'X'
if (count > 0)
str[i++] = 'X';
// copy character at current position j
// to position i and increment i and j
if (j < str.Length)
str[i++] = str[j++];
}
// add a null character to terminate string
str[i] = '\0';
}
// Driver code
public static void Main()
{
char[] str = "GeeksforGeeks".ToCharArray();
string pattern = "Geeks";
ReplacePattern(str, pattern);
Console.WriteLine(str);
}
}
// This code is contributed by codebraxnzt
JavaScript
<script>
// JavaScript program to in-place replace multiple
// occurrences of a pattern by character ‘X’
// returns true if pattern is prefix of str
function compare(str, pattern)
{
for (let i = 0; i<pattern.length; i++)
if (str[i] != pattern[i])
return false;
return true;
}
// Function to in-place replace multiple
// occurrences of a pattern by character ‘X’
function replacePattern(str,pattern)
{
// If pattern is null or empty string,
// nothing needs to be done
if (pattern == "")
return;
let len = pattern.length;
if (len == 0)
return;
let i = 0, j = 0;
let count;
// for each character
while (j<str.length) {
count = 0;
// compare str[j..j+len] with pattern
while (compare(str.substring(j,j+len), pattern)) {
// increment j by length of pattern
j = j + len;
count++;
}
// If single or multiple occurrences of pattern
// is found, replace it by character 'X'
if (count > 0){
str = str.substring(0,i) + 'X' + str.substring(i+1,)
i++
}
// copy character at current position j
// to position i and increment i and j
if (j<str.length){
str = str.substring(0,i) + str[j] + str.substring(i+1,)
i++;j++
}
}
// add a null character to terminate string
str = str.substring(0,i);
return str;
}
// Driver code
let str = "GeeksforGeeks";
let pattern = "Geeks";
str = replacePattern(str, pattern);
document.write(str,"</br>");
// This code is contributed by shinjanpatra
</script>
Time complexity: O(n*m) where n is length of string and m is length of the pattern.
Auxiliary Space: O(1)
Implementation using STL
The idea of this implementation is to use the STL in-built functions
to search for pattern string in main string and then erasing it
from the main string
C++
// C++ program to in-place replace multiple
// occurrences of a pattern by character ‘X’
#include <bits/stdc++.h>
using namespace std;
// Function to in-place replace multiple
// occurrences of a pattern by character ‘X’
void replacePattern(string str, string pattern)
{
// making an iterator for string str
string::iterator it = str.begin();
// run this loop until iterator reaches end of string
while (it != str.end()) {
// searching the first index in string str where
// the first occurrence of string pattern occurs
it = search(str.begin(), str.end(), pattern.begin(), pattern.end());
// checking if iterator is not pointing to end of the
// string str
if (it != str.end()) {
// erasing the full pattern string from that iterator
// position in string str
str.erase(it, it + pattern.size());
// inserting 'X' at that iterator position
str.insert(it, 'X');
}
}
// this loop removes consecutive 'X' in string s
// Example: GeeksGeeksforGeeks was changed to 'XXforX'
// running this loop will change it to 'XforX'
for (int i = 0; i < str.size() - 1; i++) {
if (str[i] == 'X' && str[i + 1] == 'X') {
// removing 'X' at position i in string str
str.erase(str.begin() + i);
i--; // i-- because one character was deleted
// so repositioning i
}
}
cout << str;
}
// Driver code
int main()
{
string str = "GeeksforGeeks";
string pattern = "Geeks";
replacePattern(str, pattern);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
public class GFG {
// Function to in-place replace multiple occurrences of a pattern by character ‘X’
static void replacePattern(StringBuilder str, String pattern) {
// run this loop until string str is empty
while (str.length() > 0) {
// searching the first index in string str where the first occurrence of string pattern occurs
int index = str.indexOf(pattern);
// checking if pattern is found in string str
if (index >= 0) {
// erasing the full pattern string from that index position in string str
str.delete(index, index + pattern.length());
// inserting 'X' at that index position
str.insert(index, "X");
} else {
// if pattern is not found in string str, exit loop
break;
}
}
// this loop removes consecutive 'X' in string s
// Example: GeeksGeeksforGeeks was changed to 'XXforX'
// running this loop will change it to 'XforX'
for (int i = 0; i < str.length() - 1; i++) {
if (str.charAt(i) == 'X' && str.charAt(i + 1) == 'X') {
// removing 'X' at position i in string str
str.deleteCharAt(i);
i--; // i-- because one character was deleted so repositioning i
}
}
System.out.println(str);
}
public static void main(String[] args) {
StringBuilder str = new StringBuilder("GeeksforGeeks");
String pattern = "Geeks";
replacePattern(str, pattern);
}
}
Python3
# Python program to in-place replace multiple
# occurrences of a pattern by character ‘X’
import re
# Function to in-place replace multiple
# occurrences of a pattern by character ‘X’
def replacePattern(str, pattern):
# search for the pattern in the string
while (re.search(pattern, str)):
# replace the first occurrence of pattern with 'X'
str = re.sub(pattern, 'X', str, 1)
# remove consecutive 'X' in string s
# Example: GeeksGeeksforGeeks was changed to 'XXforX'
# running this loop will change it to 'XforX'
i = 0
while (i < len(str) - 1):
if (str[i] == 'X' and str[i + 1] == 'X'):
# removing 'X' at position i in string str
str = str[:i] + str[i+1:]
else:
i += 1
print(str)
# Driver code
if __name__ == "__main__":
str = "GeeksforGeeks"
pattern = "Geeks"
replacePattern(str, pattern)
# Contributed by adityasha4x71
C#
// C# program to in-place replace multiple
// occurrences of a pattern by character ‘X’
using System;
using System.Linq;
class Gfg
{
// Function to in-place replace multiple
// occurrences of a pattern by character ‘X’
static void replacePattern(ref string str, string pattern)
{
// run this loop until string str is empty
while (str.Length > 0)
{
// searching the first index in string str where
// the first occurrence of string pattern occurs
int index = str.IndexOf(pattern);
// checking if pattern is found in string str
if (index >= 0)
{
// erasing the full pattern string from that index position in string str
str = str.Remove(index, pattern.Length);
// inserting 'X' at that index position
str = str.Insert(index, "X");
}
else
{
// if pattern is not found in string str, exit loop
break;
}
}
// this loop removes consecutive 'X' in string s
// Example: GeeksGeeksforGeeks was changed to 'XXforX'
// running this loop will change it to 'XforX'
for (int i = 0; i < str.Length - 1; i++)
{
if (str[i] == 'X' && str[i + 1] == 'X')
{
// removing 'X' at position i in string str
str = str.Remove(i, 1);
i--; // i-- because one character was deleted
// so repositioning i
}
}
Console.WriteLine(str);
}
// Driver code
static void Main(string[] args)
{
string str = "GeeksforGeeks";
string pattern = "Geeks";
replacePattern(ref str, pattern);
}
}
JavaScript
// Javascript code addition
function replacePattern(str, pattern) {
while (str.search(pattern) !== -1) {
// Replace the first occurrence of pattern with 'X'
str = str.replace(pattern, 'X');
}
// Remove consecutive 'X' in string s
// Example: GeeksGeeksforGeeks was changed to 'XXforX'
// Running this loop will change it to 'XforX'
let i = 0;
while (i < str.length - 1) {
if (str[i] === 'X' && str[i + 1] === 'X') {
// Removing 'X' at position i in string str
str = str.substring(0, i) + str.substring(i + 1);
} else {
i++;
}
}
console.log(str);
}
const str = "GeeksforGeeks";
const pattern = /Geeks/g;
replacePattern(str, pattern);
// The code is contributed by Nidhi goel.
Time Complexity: O(n*m)
Auxiliary Space: O(1)
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
PHP | ereg_replace() Function The ereg_replace() is an inbuilt function in PHP and is used to search a string pattern in an other string. If pattern is found in the original string then it will replace matching text with a replacement string. You may refer to the article on Regular Expression for basic understanding of pattern m
3 min read
PHP str_replace() Function In this article, we will see how to replace the occurrence of the search string with the replacing string using the str_replace() function in PHP, along with understanding their implementation through the examples. The str_replace() is a built-in function in PHP and is used to replace all the occurr
3 min read
Check if string follows order of characters defined by a pattern or not | Set 2 Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there wonât be any duplicate characters in the pattern.Another solution to the same problem is posted here.Examples: Input: string = "enginee
8 min read
std::regex_match, std::regex_replace() | Regex (Regular Expression) In C++ Regex is the short form for âRegular expressionâ, which is often used in this way in programming languages and many different libraries. It is supported in C++11 onward compilers.Function Templates used in regex regex_match() -This function return true if the regular expression is a match against th
3 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
JavaScript String replaceAll() Method The replaceAll() method in JavaScript is used to replace all occurrences of a specified substring or pattern with a new substring. The replaceAll() method does not change the original string.JavaScript's replaceAll() method used for replacing all instances of a specified substring or pattern within
3 min read
HTML Entity Parser Given a string str which has various HTML Entities in it, the task is to replace these entities with their corresponding special character. HTML entity parser is the parser that takes HTML code as input and replaces all the entities of the special characters by the characters itself. The special cha
15+ min read
How to Replace All Occurings of String Using Regex in Java? Regex in Java is an interesting way to search for patterns in a string that the user provides. Expanded as Regular Expressions, It consists of some patterns that can be planned and modified according to the usage in the program. Example of Replace All Occurings of a StringInput: str="This is a sampl
2 min read
Java Program to Replace Multiple Characters in a String In this program, we will be discussing various methods for replacing multiple characters in String. This can be done using the methods listed below: Using String.replace() methodUsing replaceAll() method Using replaceFirst() method Method 1: Using String.replace() method This method returns a new st
3 min read