Programa para reemplazar una palabra con asteriscos en una oración

Para la oración dada como entrada, censure una palabra específica con asteriscos ‘ * ‘. 
Ejemplo : 

Entrada: palabra = «computadora» 
texto = «GeeksforGeeks es un portal de informática para geeks. Las personas que aman la computadora y los códigos de computadora pueden contribuir con sus objetos de valor/ideas sobre códigos/estructuras de computadora aquí”. 
Salida: GeeksforGeeks es un portal de ciencia ******** para geeks. Las personas que aman los códigos ******** y ******** pueden contribuir con sus objetos de valor/ideas sobre los códigos/estructuras ******** aquí.

La idea es dividir primero la oración dada en diferentes palabras. Luego recorra la lista de palabras. Para cada palabra en la lista de palabras, verifique si coincide con la palabra dada. En caso afirmativo, reemplace la palabra con estrellas en la lista. Finalmente combine las palabras de list e print. 
 

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

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
?>

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>
Producción

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

Complejidad de tiempo : O(longitud(palabra)+M), donde M es el número de palabras en el texto

Espacio Auxiliar : O(1)

Enfoque: Usar replace() en python3.
El método Replace() busca la string pasada como primer argumento en la string dada y luego la reemplaza con el segundo argumento.

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)
Producción

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

Publicación traducida automáticamente

Artículo escrito por retr0 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *