Replacing a word in text by asterisks. - C++ STL

C++ examples for STL:string

Description

Replacing a word in text by asterisks.

Demo Code

#include <iostream>
#include <string>
#include <cctype>

using std::string;

int main()//w ww .j  a v  a  2  s.c om
{
  string text;
  string word;
  char asterisk = '*';
  std::cout << "Enter some text terminated by *:\n";
  std::getline(std::cin, text, '*');
  std::cout << "\nEnter the word to be replaced: ";
  std::cin >> word;
  string uc_word{ word };

  for (auto& ch : uc_word)
    ch = std::toupper(ch);

  const string separators{ " ,;:.\"!?'\n" };                  // Word  delimiters

  unsigned int start{ text.find_first_not_of(separators) };
  int end{};
  bool is_word{ false };

  while (start != string::npos)
  {
    end = text.find_first_of(separators, start + 1);
    if (end == string::npos)
      end = text.length();

    // Compare the word found in uppercase with uc_word
    if (end - start == word.length())
    {
      is_word = true;
      for (unsigned int i{ start }; i < end; ++i)
        if (uc_word[i - start] != toupper(text[i]))
        {
          is_word = false;
          break;
        }
      if (is_word)
        for (unsigned int i{ start }; i < end; ++i)
          text[i] = asterisk;
    }
    start = text.find_first_not_of(separators, end + 1);
  }

  std::cout << std::endl << text << std::endl;
}

Result


Related Tutorials