C++ Program to replace a word with asterisks in a sentence

Hello everyone, in this tutorial, we will write a C++ program to replace a word with asterisks in a sentence.

Below is the given C++ code that will replace the specific word with asterisks:

#include<iostream> 
#include <string>
#include <boost/algorithm/string.hpp> 

using namespace std; 

string rep_astreik(string sentence , string replace) 
{ 
  vector<string> word_list;
  
  boost::split(word_list, sentence, boost::is_any_of(" "));  //split the senetence
 
  string asterisks = ""; 
    int n = replace.size();     //find the size of word to be replaced
  
  for (int i = 0; i < n ; i++) 
    asterisks += '*'; 

  int index = 0; 
  
  for (string i : word_list)      //compare list with the word if found same replace asterisks
  { 
    if (i.compare(replace) == 0) 
    { 
      word_list[index] = asterisks; 
    } 
    index++; 
  } 
  
  string result = "";
    
  for (string i : word_list) //forming the sentence from the words in the vector 
  { 
    result += i + ' '; 
  } 
  return result; 
} 

int main() 
{ 
  std::string sentence ;
  std::string replace ;
  std::cout<<"Enter the sentence : ";
  getline (std::cin , sentence);
  std::cout<<"Enter the word to replace with astreik : ";
  getline(std::cin , replace);
  string result =  (rep_astreik(sentence, replace)); 
  std::cout<<"After replacement of "<<replace<<" with * : ";
  std::cout<<result;
} 


Output:

Enter the sentence : C++ was developed by  Bjarne Stroustrup. C++ is extension of C. 
Enter the word to replace with astreik : C++ 
After replacement of C++ with * : *** was developed by  Bjarne Stroustrup . *** is extension of C.

Explanation:

  1. Declare two string variables, one for accepting the sentence and other for accepting the word that is to be replaced with asterisk.
  2. Then pass both the strings as a parameter to the function rep_astreisk.
  3. In rep_asterisk function, firstly declare a vector of string type so that we can store all the words in it.
  4. With the help of split function, we will split the sentence into the words and store in word_list vector.
  5. We find the size of the word to be replaced so that we can get an exact number of asterisks to be placed instead of that word.
  6. Now, we will travel the whole vector and check if any of the word matches to word to be replaced. If found, replace it with asterisks, else move forward.
  7. Now, in vector word_list we have list of all the words including the asterisks that have replaced the given word.
  8. Now, we will form a sentence from the words in the vector along with the spaces between them and store in result.
  9. Finally display it.

 

Also read,

Leave a Reply

Your email address will not be published. Required fields are marked *