Replace all occurrences of a string with space
Last Updated :
16 Sep, 2023
Given a string and a substring, the task is to replace all occurrences of the substring with space. We also need to remove trailing and leading spaces created due to this.
Examples:
Input: str = “LIELIEILIEAMLIECOOL”, sub = “LIE”
Output: I AM COOL By replacing all occurrences of Sub in Str with empty spaces, we extract the secret message as I AM COOL.
Input: str = “XYZAXYZBXYZC”, sub = “XYZ”
Output: ABC By replacing all occurrences of Sub in Str with empty spaces, we extract the secret message as ABC.
Approach:
- In the given string Str, replace all occurrences of Sub with empty spaces.
- Remove unwanted empty spaces in start and end of the string.
- Print the modified string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string trim( const string &s)
{
auto start = s.begin();
while (start != s.end() &&
isspace (*start))
start++;
auto end = s.end();
do
{
end--;
} while (distance(start, end) > 0 &&
isspace (*end));
return string(start, end + 1);
}
string extractSecretMessage(string str,
string sub)
{
size_t pos;
while ((pos = str.find(sub)) != string::npos)
str.replace(pos, 3, " " );
str = trim(str);
return str;
}
int main( int argc, char const *argv[])
{
string str = "LIELIEILIEAMLIECOOL" ;
string sub = "LIE" ;
cout << extractSecretMessage(str, sub)
<< endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static String extractSecretMessage(String Str, String Sub)
{
Str = Str.replaceAll(Sub, " " );
Str = Str.trim();
return Str;
}
public static void main(String args[])
{
String Str = "LIELIEILIEAMLIECOOL" ;
String Sub = "LIE" ;
System.out.println(extractSecretMessage(Str, Sub));
}
}
|
Python3
def extractSecretMessage( Str , Sub):
Str = Str .replace(Sub, " " )
return Str .strip()
Str = "LIELIEILIEAMLIECOOL"
Sub = "LIE"
print (extractSecretMessage( Str , Sub))
|
C#
using System;
class GFG
{
static string extractSecretMessage( string Str,
string Sub)
{
Str = Str.Replace(Sub, " " );
Str = Str.Trim();
return Str;
}
public static void Main()
{
string Str = "LIELIEILIEAMLIECOOL" ;
string Sub = "LIE" ;
Console.WriteLine(extractSecretMessage(Str, Sub));
}
}
|
Javascript
function extractSecretMessage(Str, Sub) {
let i = 0, n = Str.length;
let k = Sub.length;
while (i < n) {
Str = (Str.replace(Sub, " " ));
i += k;
}
return Str.trim();
}
let Str = " LIELIEILIEAMLIECOOL" ;
let Sub = "LIE" ;
console.log(extractSecretMessage(Str, Sub));
|
PHP
<?php
function extractSecretMessage( $Str , $Sub )
{
$Str = str_replace ( $Sub , " " , $Str );
return trim( $Str );
}
$Str = "LIELIEILIEAMLIECOOL" ;
$Sub = "LIE" ;
echo extractSecretMessage( $Str , $Sub );
?>
|
Complexity Analysis:
- Time Complexity: O(N), as we are using replace function which will cost us O(N) time.
- Auxiliary Space: O(1), as we are not using any extra space.
Approach:
- Initialize an empty string called result.
- Loop through the input string str, and for each character.
- Check if the current character is the same as the first character of the substring sub. If so, check if the next characters match with the substring. If there is a match, skip the characters that match with the substring and add a space to the result string.
- If the current character is not the same as the first character of the substring, add it to the result string.
- Trim the result string to remove leading and trailing spaces.
- Return the result string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string extractSecretMessage(string str, string sub) {
string result;
int n = str.length(), m = sub.length(), i = 0;
while (i < n) {
if (str[i] == sub[0] && str.substr(i, m) == sub) {
result += " " ;
i += m;
} else {
result += str[i];
i++;
}
}
auto start = result.begin();
while (start != result.end() && isspace (*start))
start++;
auto end = result.end();
do {
end--;
} while (distance(start, end) > 0 && isspace (*end));
return string(start, end + 1);
}
int main() {
string str = "LIELIEILIEAMLIECOOL" ;
string sub = "LIE" ;
cout << extractSecretMessage(str, sub) << endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
String str = "LIELIEILIEAMLIECOOL" ;
String sub = "LIE" ;
System.out.println(extractSecretMessage(str, sub));
}
public static String extractSecretMessage(String str, String sub) {
StringBuilder result = new StringBuilder();
int n = str.length();
int m = sub.length();
int i = 0 ;
while (i < n) {
if (str.charAt(i) == sub.charAt( 0 ) && i + m <= n && str.substring(i, i + m).equals(sub)) {
result.append( " " );
i += m;
} else {
result.append(str.charAt(i));
i++;
}
}
String trimmedResult = result.toString().trim();
return trimmedResult;
}
}
|
Python3
def extract_secret_message(s, sub):
result = []
n = len (s)
m = len (sub)
i = 0
while i < n:
if s[i] = = sub[ 0 ] and i + m < = n and s[i:i + m] = = sub:
result.append( " " )
i + = m
else :
result.append(s[i])
i + = 1
trimmed_result = ''.join(result).strip()
return trimmed_result
str_input = "LIELIEILIEAMLIECOOL"
sub_input = "LIE"
print (extract_secret_message(str_input, sub_input))
|
C#
using System;
using System.Text;
public class GFG
{
public static void Main( string [] args)
{
string str = "LIELIEILIEAMLIECOOL" ;
string sub = "LIE" ;
Console.WriteLine(ExtractSecretMessage(str, sub));
}
public static string ExtractSecretMessage( string str, string sub)
{
StringBuilder result = new StringBuilder();
int n = str.Length;
int m = sub.Length;
int i = 0;
while (i < n)
{
if (str[i] == sub[0] && i + m <= n && str.Substring(i, m) == sub)
{
result.Append( " " );
i += m;
}
else
{
result.Append(str[i]);
i++;
}
}
string trimmedResult = result.ToString().Trim();
return trimmedResult;
}
}
|
Javascript
function extractSecretMessage(str, sub) {
let result = '' ;
let n = str.length;
let m = sub.length;
let i = 0;
while (i < n) {
if (str[i] === sub[0] && str.substring(i, i + m) === sub) {
result += ' ' ;
i += m;
} else {
result += str[i];
i++;
}
}
let start = 0;
while (start < result.length && result[start] === ' ' )
start++;
let end = result.length - 1;
while (end >= start && result[end] === ' ' )
end--;
return result.substring(start, end + 1);
}
function main() {
let str = 'LIELIEILIEAMLIECOOL' ;
let sub = 'LIE' ;
console.log(extractSecretMessage(str, sub));
}
main();
|
Time Complexity: O(n * m), where n is the length of the input string and m is the length of the substring to be replaced. This is because we are iterating over the input string and comparing substrings of length m with the given substring.
Auxiliary Space: O(n) because we are using an additional string ‘result’ to store the modified string.
Share your thoughts in the comments
Please Login to comment...