Advertisement
drankinatty

Censor Input - Find/Replace each word of given length

Jan 17th, 2019
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. /** censor input (generic challenge question)
  2.  *  replaces all words that are the same length as the replacement string
  3.  *  provided as argv[1] (default "****") outputting each line with an
  4.  *  intervening newline (blank line).
  5.  */
  6. #include <iostream>
  7. #include <sstream>
  8. #include <string>
  9.  
  10. int main (int argc, char **argv) {
  11.    
  12.     std::string line;   /* string to hold each line */
  13.     const std::string repl = argc > 1 ? argv[1] : "****";   /* replacement */
  14.    
  15.     while (getline (std::cin, line)) {      /* read each line */
  16.         std::string word;                   /* string to hold each word */
  17.         std::stringstream s (line);         /* stringstream to parse line */
  18.         while (s >> word)                   /* read each word */
  19.             if (word.length() == repl.length()) /* lengths equal, replace */
  20.                 line.replace (line.find (word, 0), repl.length(), repl);
  21.         std::cout << line << "\n\n";        /* output newlines */
  22.     }
  23. }
  24.  
  25. /*
  26.  
  27. **Example Input**
  28.  
  29.     $ cat ../dat/captnjack.txt
  30.     This is a tale
  31.     Of Captain Jack Sparrow
  32.     A Pirate So Brave
  33.     On the Seven Seas.
  34.  
  35.  
  36. **Example Use/Output**
  37.  
  38.     $ ./getline_repl < ../dat/captnjack.txt
  39.     **** is a ****
  40.    
  41.     Of Captain **** Sparrow
  42.    
  43.     A Pirate So Brave
  44.    
  45.     On the Seven Seas.
  46.  
  47.  
  48.   Specifying the replacement as the 1st program argument
  49.  
  50.     $ ./getline_repl +++++ < ../dat/captnjack.txt
  51.     This is a tale
  52.    
  53.     Of Captain Jack Sparrow
  54.    
  55.     A Pirate So +++++
  56.    
  57.     On the +++++ +++++
  58.  
  59.  
  60. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement