C++ string Replacing a word in text by asterisks.
#include <iostream> #include <string> #include <cctype> using std::string; int main()//from www .j a v a 2 s .co m { 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 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 (int i {start}; i < end; ++i) if (uc_word[i - start] != toupper(text[i])) { is_word = false; break; } if (is_word) for (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; }