Open In App

Program to replace a word with asterisks in a sentence

Last Updated : 07 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

For the given sentence as input, censor a specific word with asterisks ‘ * ‘. 

Example : 

Input : word = “computer” 
text = “GeeksforGeeks is a computer science portal for geeks. People who love computer and computer codes can contribute their valuables/ideas on computer codes/structures on here.” 
Output : GeeksforGeeks is a ******** science portal for geeks. People who love ******** and ******** codes can contribute their valuables/ideas on ******** codes/structures on here.

The idea is to first split given sentence into different words. Then traverse the word list. For every word in the word list, check if it matches with given word. If yes, then replace the word with stars in the list. Finally merge the words of list and print. 

Implementation:

C++




// C++ program to censor a word
// with asterisks in a sentence
#include<bits/stdc++.h>
#include <boost/algorithm/string.hpp>
using namespace std;
 
// Function takes two parameter
string censor(string text,
                    string word)
{
 
    // Break down sentence by ' ' spaces
    // and store each individual word in
    // a different list
    vector<string> word_list;
    boost::split(word_list, text, boost::is_any_of("\\ +"));
 
    // A new string to store the result
    string result = "";
 
    // Creating the censor which is an asterisks
    // "*" text of the length of censor word
    string stars = "";
    for (int i = 0; i < word.size(); i++)
        stars += '*';
 
    // Iterating through our list
    // of extracted words
    int index = 0;
    for (string i : word_list)
    {
         
        if (i.compare(word) == 0)
        {
 
            // changing the censored word to
            // created asterisks censor
            word_list[index] = stars;
        }
        index++;
    }
 
    // join the words
    for (string i : word_list)
    {
        result += i + ' ';
    }
    return result;
}
 
// Driver code
int main()
{
    string extract = "GeeksforGeeks is a computer science "
                    "portal for geeks. I am pursuing my "
                    "major in computer science. ";
    string cen = "computer";
    cout << (censor(extract, cen));
}
 
// This code is contributed by Rajput-Ji


Java




// Java program to censor a word
// with asterisks in a sentence
class GFG
{
 
// Function takes two parameter
static String censor(String text,
                     String word)
{
 
    // Break down sentence by ' ' spaces
    // and store each individual word in
    // a different list
    String[] word_list = text.split("\\s+");
 
    // A new string to store the result
    String result = "";
 
    // Creating the censor which is an asterisks
    // "*" text of the length of censor word
    String stars = "";
    for (int i = 0; i < word.length(); i++)
        stars += '*';
 
    // Iterating through our list
    // of extracted words
    int index = 0;
    for (String i : word_list)
    {
        if (i.compareTo(word) == 0)
 
            // changing the censored word to
            // created asterisks censor
            word_list[index] = stars;
        index++;
    }
 
    // join the words
    for (String i : word_list)
        result += i + ' ';
 
    return result;
}
 
// Driver code
public static void main(String[] args)
{
    String extract = "GeeksforGeeks is a computer science "+
                     "portal for geeks. I am pursuing my " +
                     "major in computer science. ";
    String cen = "computer";
    System.out.println(censor(extract, cen));
}
}
 
// This code is contributed by
// sanjeev2552


Python3




# Python Program to censor a word
# with asterisks in a sentence
 
 
# Function takes two parameter
def censor(text, word):
 
    # Break down sentence by ' ' spaces
    # and store each individual word in
    # a different list
    word_list = text.split()
 
    # A new string to store the result
    result = ''
 
    # Creating the censor which is an asterisks
    # "*" text of the length of censor word
    stars = '*' * len(word)
 
    # count variable to
    # access our word_list
    count = 0
 
    # Iterating through our list
    # of extracted words
    index = 0;
    for i in word_list:
 
        if i == word:
             
            # changing the censored word to
            # created asterisks censor
            word_list[index] = stars
        index += 1
 
    # join the words
    result =' '.join(word_list)
 
    return result
 
# Driver code
if __name__== '__main__':
     
    extract = "GeeksforGeeks is a computer science portal for geeks.\
               I am pursuing my major in computer science. "              
    cen = "computer"   
    print(censor(extract, cen))


C#




// C# program to censor a word
// with asterisks in a sentence
using System;
using System.Collections.Generic;
     
class GFG
{
 
// Function takes two parameter
static String censor(String text,
                     String word)
{
 
    // Break down sentence by ' ' spaces
    // and store each individual word in
    // a different list
    String[] word_list = text.Split(' ');
 
    // A new string to store the result
    String result = "";
 
    // Creating the censor which is an asterisks
    // "*" text of the length of censor word
    String stars = "";
    for (int i = 0; i < word.Length; i++)
        stars += '*';
 
    // Iterating through our list
    // of extracted words
    int index = 0;
    foreach (String i in word_list)
    {
        if (i.CompareTo(word) == 0)
 
            // changing the censored word to
            // created asterisks censor
            word_list[index] = stars;
        index++;
    }
 
    // join the words
    foreach (String i in word_list)
        result += i + " ";
 
    return result;
}
 
// Driver code
public static void Main(String[] args)
{
    String extract = "GeeksforGeeks is a computer science "+
                     "portal for geeks. I am pursuing my " +
                     "major in computer science. ";
    String cen = "computer";
    Console.WriteLine(censor(extract, cen));
}
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
      // JavaScript program to censor a word
      // with asterisks in a sentence
       
      // Function takes two parameter
      function censor(text, word) {
        // Break down sentence by ' ' spaces
        // and store each individual word in
        // a different list
        var word_list = text.split(" ");
 
        // A new string to store the result
        var result = "";
 
        // Creating the censor which is an asterisks
        // "*" text of the length of censor word
        var stars = "";
        for (var i = 0; i < word.length; i++) stars += "*";
 
        // Iterating through our list
        // of extracted words
        var index = 0;
        for (const i of word_list) {
          if (i === word)
            // changing the censored word to
            // created asterisks censor
            word_list[index] = stars;
          index++;
        }
 
        // join the words
        for (const i of word_list) {
          result += i + " ";
        }
 
        return result;
      }
 
      // Driver code
      var extract =
        "GeeksforGeeks is a computer science " +
        "portal for geeks. I am pursuing my " +
        "major in computer science. ";
         
      var cen = "computer";
      document.write(censor(extract, cen) + "<br>");
       
</script>


PHP




<?php
// PHP Program to censor a word
// with asterisks in a sentence
 
// Function takes two parameter
function censor($text, $word)
{
 
    // Break down sentence by ' ' spaces
    // and store each individual word in
    // a different list
    $word_list = explode(" ", $text);
 
    // A new string to store the result
    $result = '';
 
    // Creating the censor which is an
    // asterisks "*" text of the length
    // of censor word
    $stars = "";
    for($i = 0; $i < strlen($word); $i++)
    $stars .= "*";
 
    // count variable to access
    // our word_list
    $count = 0;
 
    // Iterating through our list of
    // extracted words
    $index = 0;
    for($i = 0; $i < sizeof($word_list); $i++)
    {
        if($word_list[$i] == $word)
             
            // changing the censored word to
            // created asterisks censor
            $word_list[$index] = $stars;
        $index += 1;
    }
     
    // join the words
    return implode(' ', $word_list);
}
 
// Driver code
$extract = "GeeksforGeeks is a computer science ".
           "portal for geeks.\nI am pursuing my ".
                    "major in computer science. ";        
$cen = "computer";
echo censor($extract, $cen);
 
// This code is contributed
// by Aman ojha
?>


Output

GeeksforGeeks is a ******** science portal for geeks. I am pursuing my major in ******** science.  









Complexity Analysis:

  • Time complexity: O(length(word)+M), where M is the number of words in text
  • Auxiliary Space: O(1)

Approach : Using replace() in python3.
Replace() method searches for the string passed as the first argument in the given string and then replaces that with the second argument.

Implementation:

C++




#include <iostream>
#include <string>
 
int main()
{
    // Input sentence
    std::string extract
        = "GeeksforGeeks is a computer science portal for "
          "geeks. I am pursuing my major in computer "
          "science.";
 
    // Word to censor
    std::string cen = "computer";
 
    // Find the position of the word to censor
    size_t found = extract.find(cen);
 
    // While the word is found, replace it with asterisks
    while (found != std::string::npos) {
        extract.replace(found, cen.length(),
                        std::string(cen.length(), '*'));
        found = extract.find(cen, found + cen.length());
    }
 
    // Print the censored sentence
    std::cout << extract << std::endl;
 
    return 0;
}


Java




public class CensorWordInSentence {
    public static void main(String[] args)
    {
        // Input sentence
        String extract
            = "GeeksforGeeks is a computer science portal for geeks. I am pursuing my major in computer science.";
 
        // Word to censor
        String cen = "computer";
 
        // Replace the word with asterisks
        extract = extract.replace(cen,
                                  "*".repeat(cen.length()));
 
        // Print the censored sentence
        System.out.println(extract);
    }
}


Python3




# Python Program to censor a word
# with asterisks in a sentence
 
extract = "GeeksforGeeks is a computer science portal for geeks.I am pursuing my major in computer science. "           
cen = "computer"
extract=extract.replace(cen,'*'*len(cen))
print(extract)


C#




using System;
 
class Program {
    static void Main()
    {
        // Input sentence
        string extract
            = "GeeksforGeeks is a computer science portal for "
              + "geeks. I am pursuing my major in computer "
              + "science.";
 
        // Word to censor
        string cen = "computer";
 
        // Find the position of the word to censor
        int found = extract.IndexOf(
            cen, StringComparison.OrdinalIgnoreCase);
 
        // While the word is found, replace it with
        // asterisks
        while (found != -1) {
            extract
                = extract.Remove(found, cen.Length)
                      .Insert(found,
                              new string('*', cen.Length));
            found = extract.IndexOf(
                cen, found + cen.Length,
                StringComparison.OrdinalIgnoreCase);
        }
 
        // Print the censored sentence
        Console.WriteLine(extract);
    }
}


Javascript




// JavaScript Program to censor a word
// with asterisks in a sentence
 
let extract = "GeeksforGeeks is a computer science portal for geeks.I am pursuing my major in computer science.";
let cen = "computer";
extract = extract.replace(new RegExp(cen, 'gi'), '*'.repeat(cen.length));
console.log(extract);
 
// This code is contributed by codebraxnzt


Output

GeeksforGeeks is a ******** science portal for geeks.\I am pursuing my major in ******** science. 









Using re module:

You can use the re module in Python to search for the specific word in the sentence and replace it with the asterisks.

Using 

The censor function takes two parameters, text and word. 

It searches for all occurrences of word in text using a regular expression with the global g flag, and replaces each occurrence with asterisks of the same length using the replace function.

C++




#include <iostream>
#include <regex>
 
std::string censor(const std::string& text,
                   const std::string& word)
{
    // Use the regex_replace function to search for the word
    // in the text and replace it with asterisks of the same
    // length
    std::regex pattern(word);
    std::string result = std::regex_replace(
        text, pattern, std::string(word.length(), '*'));
    return result;
}
 
// Test the function
int main()
{
    std::string text
        = "GeeksforGeeks is a computer science portal for "
          "geeks. I am pursuing my major in computer "
          "science.";
    std::string word = "computer";
    std::cout << censor(text, word) << std::endl;
    return 0;
}


Java




import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class Main {
    public static String censor(String text, String word)
    {
        // Use the replaceAll function in the Matcher class
        // to search for the word in the text and replace it
        // with the asterisks of the same length
        Pattern pattern = Pattern.compile(word);
        Matcher matcher = pattern.matcher(text);
        String result
            = matcher.replaceAll("*".repeat(word.length()));
        return result;
    }
 
    // Test the function
    public static void main(String[] args)
    {
        String text
            = "GeeksforGeeks is a computer science portal for geeks. I am pursuing my major in computer science.";
        String word = "computer";
        System.out.println(censor(text, word));
    }
}
// This code is contributed by Prajwal Kandekar


Python3




import re
 
def censor(text, word):
    # Use the sub function in the re module to search for the word in the text
    # and replace it with the asterisks of the same length
    result = re.sub(word, '*' * len(word), text)
    return result
 
# Test the function
text = "GeeksforGeeks is a computer science portal for geeks. I am pursuing my major in computer science."
word = "computer"
print(censor(text, word))


C#




using System;
using System.Text.RegularExpressions;
 
class MainClass {
    public static string Censor(string text, string word) {
        // Use the Replace method in the Regex class
        // to search for the word in the text and replace it
        // with the asterisks of the same length
        Regex regex = new Regex(Regex.Escape(word));
        string result = regex.Replace(text, new string('*', word.Length));
        return result;
    }
 
    // Test the function
    public static void Main (string[] args) {
        string text = "GeeksforGeeks is a computer science portal for geeks. I am pursuing my major in computer science.";
        string word = "computer";
        Console.WriteLine(Censor(text, word));
    }
}


Javascript




// JavaScript Program for the above approach
 
function censor(text, word) {
  // Use the replace method with a regular expression to search for the word in the text
  // and replace it with the asterisks of the same length
  const regex = new RegExp(word, 'gi');
  const result = text.replace(regex, '*'.repeat(word.length));
  return result;
}
 
// Test the function
const text = "GeeksforGeeks is a computer science portal for geeks. I am pursuing my major in computer science.";
const word = "computer";
console.log(censor(text, word));
 
// This code is contributed by princekumaras


Output

GeeksforGeeks is a ******** science portal for geeks. I am pursuing my major in ******** science.









This approach has a time complexity of O(N), where N is the length of the text. The auxiliary space required is O(1).

Using regular expression

In the regular expression, we pass the word variable as the pattern to search for. The g flag means that it will find all occurrences of the pattern, not just the first one.

In the replace function, we pass a callback function that returns an asterisk (*) repeated for the length of the matched string. 

This ensures that the asterisks have the same length as the word that was replaced.

C++




#include <bits/stdc++.h>
using namespace std;
 
// C++ program to censor words in text
string censor(string text, string word)
{
   
    // Use the regex_replace function in
  /// the regex library to search for the word in the text
    // and replace it with the asterisks of the same length
    regex r(word);
    string result = regex_replace(text, r, string(word.length(), '*'));
    return result;
}
 
// Test the function
int main() {
    string text = "GeeksforGeeks is a computer science portal for geeks. I am pursuing my major in computer science.";
    string word = "computer";
    cout << censor(text, word) <<endl;
    return 0;
}


Java




import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class CensorText {
     
    // Java program to censor words in text
    public static String censor(String text, String word) {
        // Use the Pattern and Matcher classes to search for the word in the text
        // and replace it with asterisks of the same length
        Pattern pattern = Pattern.compile("\\b" + word + "\\b");
        Matcher matcher = pattern.matcher(text);
         
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String replacement = new String(new char[word.length()]).replace('\0', '*');
            matcher.appendReplacement(result, replacement);
        }
        matcher.appendTail(result);
         
        return result.toString();
    }
 
    public static void main(String[] args) {
        String text = "GeeksforGeeks is a computer science portal for geeks. I am pursuing my major in computer science.";
        String word = "computer";
        System.out.println(censor(text, word));
    }
}


Python3




# Python program to censor words in text
def censor(text, word):
    # Use the replace function in the String object to search for the word in the text
    # and replace it with the asterisks of the same length
    result = text.replace(word, "*"*len(word))
    return result
 
# Test the function
text = "GeeksforGeeks is a computer science portal for geeks. I am pursuing my major in computer science."
word = "computer"
print(censor(text, word))


C#




using System;
using System.Text.RegularExpressions;
 
class Program
{
    // C# program to censor words in text
    static string Censor(string text, string word)
    {
        // Use the Regex.Replace method to search for the word in the text
        // and replace it with the asterisks of the same length
        string result = Regex.Replace(text, word, new string('*', word.Length));
        return result;
    }
 
    // Test the function
    static void Main()
    {
        string text = "GeeksforGeeks is a computer science portal for geeks.I am pursuing my major in computer science.";
        string word = "computer";
        Console.WriteLine(Censor(text, word));
    }
}


Javascript




// JavaScript program to censor words in text
function censor(text, word) {
    // Use the replace function in the String object to search for the word in the text
    // and replace it with the asterisks of the same length
    const regex = new RegExp(word, "g");
    const result = text.replace(regex, "*".repeat(word.length));
    return result;
}
 
// Test the function
const text = "GeeksforGeeks is a computer science portal for geeks. I am pursuing my major in computer science.";
const word = "computer";
console.log(censor(text, word));
 
// Contributed by adityasharmadev01


Output

GeeksforGeeks is a ******** science portal for geeks. I am pursuing my major in ******** science.









Time complexity: O(n), where n is the length of the input text string. 

Space complexity: O(1).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads