Replace all occurrences of a string with space (original) (raw)

Last Updated : 11 Jul, 2025

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:

Below is the implementation of the above approach:

C++ `

// C++ implementation to extract // the secret message #include <bits/stdc++.h> using namespace std;

// Trim method implementation to remove // trailing and leading white-spaces 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);

}

// Function to extract the secret message string extractSecretMessage(string str, string sub) { // Replacing all occurrences of // Sub in Str by empty spaces size_t pos; while ((pos = str.find(sub)) != string::npos) str.replace(pos, 3, " ");

// Removing unwanted spaces in the
// start and end of the string
str = trim(str);

return str;

}

// Driver code int main(int argc, char const *argv[]) { string str = "LIELIEILIEAMLIECOOL"; string sub = "LIE"; cout << extractSecretMessage(str, sub) << endl; return 0; }

// This code is contributed by // sanjeev2552

Java

// Java implementation to extract the secret message import java.io.; import java.util.;

class GFG {

// Function to extract the secret message
static String extractSecretMessage(String Str, String Sub)
{
    // Replacing all occurrences of
    // Sub in Str by empty spaces
    Str = Str.replaceAll(Sub, " ");

    // Removing unwanted spaces in the
    // start and end of the string
    Str = Str.trim();

    return Str;
}

// Driver code
public static void main(String args[])
{
    String Str = "LIELIEILIEAMLIECOOL";
    String Sub = "LIE";
    System.out.println(extractSecretMessage(Str, Sub));
}

}

Python3

Python3 implementation to extract

the secret message

Function to extract the secret message

def extractSecretMessage(Str, Sub):

# Replacing all occurrences of
# Sub in Str by empty spaces
Str= Str.replace(Sub, " ")

# Removing unwanted spaces in the
# start and end of the string

return Str.strip()

Driver code

Str = "LIELIEILIEAMLIECOOL" Sub = "LIE" print(extractSecretMessage(Str, Sub))

This code is contributed

by ihritik

C#

// C# implementation to extract the // secret message using System;

class GFG {

// Function to extract the secret message static string extractSecretMessage(string Str, string Sub) { // Replacing all occurrences of // Sub in Str by empty spaces Str = Str.Replace(Sub, " ");

// Removing unwanted spaces in the 
// start and end of the string 
Str = Str.Trim(); 

return Str; 

}

// Driver code public static void Main() { string Str = "LIELIEILIEAMLIECOOL"; string Sub = "LIE"; Console.WriteLine(extractSecretMessage(Str, Sub)); } }

// This code is contributed by Ryuga

JavaScript

// Javascript implementation to extract // the secret message

// Function to extract the secret message function extractSecretMessage(Str, Sub) {

//  Replacing all occurrences of
//  Sub in Str by empty spaces
let i = 0, n = Str.length;
let k = Sub.length;
while(i < n) {
    Str = (Str.replace(Sub, " "));
    i += k;
}

// Removing unwanted spaces in the
// start and end of the string
return Str.trim();

}

// Driver code let Str = " LIELIEILIEAMLIECOOL"; let Sub = "LIE"; console.log(extractSecretMessage(Str, Sub));

// This code is contributed // by Samim Hossain Mondal

PHP

Str=strreplace(Str = str_replace(Str=strreplace(Sub, " ", $Str); // Removing unwanted spaces in the // start and end of the string return trim($Str); } // Driver code $Str = "LIELIEILIEAMLIECOOL"; $Sub = "LIE"; echo extractSecretMessage($Str, $Sub); // This code is contributed // by ihritik ?>

`

**Complexity Analysis:

**Approach:

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++;
    }
}

// Trim the result string
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; // Output: I AM COOL 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)); // Output: I AM COOL }

// Function to extract the secret message from a given string 'str' by removing all occurrences of 'sub'
public static String extractSecretMessage(String str, String sub) {
    StringBuilder result = new StringBuilder(); // Initialize an empty StringBuilder to store the extracted secret message
    int n = str.length(); // Get the length of the input string 'str'
    int m = sub.length(); // Get the length of the substring 'sub' we want to remove from 'str'
    int i = 0; // Initialize a pointer 'i' to traverse through the input string 'str'

    // Loop through the input string 'str'
    while (i < n) {
        // Check if the current character matches the first character of the substring 'sub'
        // and if the remaining substring from the current position has enough characters to match 'sub'
        if (str.charAt(i) == sub.charAt(0) && i + m <= n && str.substring(i, i + m).equals(sub)) {
            result.append(" "); // If a match is found, append a space to the result (to separate words)
            i += m; // Move the pointer 'i' to skip the substring 'sub' in 'str'
        } else {
            // If no match is found, append the current character from 'str' to the result
            result.append(str.charAt(i));
            i++; // Move the pointer 'i' to the next character in 'str'
        }
    }

    // Convert the result StringBuilder to a String and remove any leading or trailing spaces
    String trimmedResult = result.toString().trim();

    // Return the extracted secret message
    return trimmedResult;
}

}

Python3

def extract_secret_message(s, sub): result = [] # Initialize an empty list to store the extracted secret message n = len(s) # Get the length of the input string 's' m = len(sub) # Get the length of the substring 'sub' we want to remove from 's' i = 0 # Initialize a pointer 'i' to traverse through the input string 's'

# Loop through the input string 's'
while i < n:
    # Check if the current character matches the first 
    # character of the substring 'sub'
    # and if the remaining substring from the current 
    # position has enough characters to match 'sub'
    if s[i] == sub[0] and i + m <= n and s[i:i + m] == sub:
        # If a match is found, append a space to the result (to separate words)
        result.append(" ")
        i += m  # Move the pointer 'i' to skip the substring 'sub' in 's'
    else:
        # If no match is found, append the current character from 's' to the result
        result.append(s[i])
        i += 1  # Move the pointer 'i' to the next character in 's'

# Convert the result list to a string and remove any leading or trailing spaces
trimmed_result = ''.join(result).strip()

# Return the extracted secret message
return trimmed_result

Test case

str_input = "LIELIEILIEAMLIECOOL" sub_input = "LIE" print(extract_secret_message(str_input, sub_input)) # Output: "I AM COOL"

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)); // Output: I AM COOL }

// Function to extract the secret message from a given string 'str' by removing all occurrences of 'sub'
public static string ExtractSecretMessage(string str, string sub)
{
    StringBuilder result = new StringBuilder(); // Initialize an empty StringBuilder to store the extracted secret message
    int n = str.Length; // Get the length of the input string 'str'
    int m = sub.Length; // Get the length of the substring 'sub' we want to remove from 'str'
    int i = 0; // Initialize a pointer 'i' to traverse through the input string 'str'

    // Loop through the input string 'str'
    while (i < n)
    {
        // Check if the current character matches the first character of the substring 'sub'
        // and if the remaining substring from the current position has enough characters to match 'sub'
        if (str[i] == sub[0] && i + m <= n && str.Substring(i, m) == sub)
        {
            result.Append(" "); // If a match is found, append a space to the result (to separate words)
            i += m; // Move the pointer 'i' to skip the substring 'sub' in 'str'
        }
        else
        {
            // If no match is found, append the current character from 'str' to the result
            result.Append(str[i]);
            i++; // Move the pointer 'i' to the next character in 'str'
        }
    }

    // Convert the result StringBuilder to a String and remove any leading or trailing spaces
    string trimmedResult = result.ToString().Trim();

    // Return the extracted secret message
    return trimmedResult;
}

}

// This code is contributed by akshitaguprzj3

JavaScript

// Function to extract a secret message from a given string function extractSecretMessage(str, sub) { let result = ''; // To store the extracted secret message let n = str.length; // Length of the input string let m = sub.length; // Length of the substring to search for let i = 0; // Index for traversing the input string

while (i < n) {
    if (str[i] === sub[0] && str.substring(i, i + m) === sub) {
        result += ' ';  // Add a space to separate secret words
        i += m;  // Move the index to skip the found substring
    } else {
        result += str[i];  // Append the current character to the result
        i++;  // Move to the next character
    }
}

// Trim the result string to remove leading and trailing spaces
let start = 0;
while (start < result.length && result[start] === ' ')
    start++;

let end = result.length - 1;
while (end >= start && result[end] === ' ')
    end--;

// Return the trimmed secret message
return result.substring(start, end + 1);

}

// Main function function main() { let str = 'LIELIEILIEAMLIECOOL'; let sub = 'LIE'; console.log(extractSecretMessage(str, sub)); // Output: I AM COOL }

// Call the main function to run the code main();

// This code is contributed by rambabuguphka

`

**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.