I want a function that takes a string and replaces all occurrences of a given word with asterisks in place of its letters. I want to do this elegantly, like a real C++ programmer.
As an example,
int main()
{
std::string str = "crap this craping shit.";
censor_word("crap", str);
std::cout << str;
return 0;
}
should output
"**** this ****ing shit"
I need help coming up with an elegant way of filling in the following function:
void censor_word(const std::string& word, std::string& text)
{
...
}
I know the geniuses at Stack Overflow can probably come up with a 1-line solution.
My code looks yucky
void censor_word(const std::string& word, std::string& text)
{
int wordsize= word.size();
if (wordsize < text.size())
{
for (std::string::iterator it(text.begin()), endpos(text.size() - wordsize), int curpos = 0; it != endpos; ++it, ++curpos)
{
if (text.substr(curpos, wordsize) == word)
{
std::string repstr(wordsize, '*');
text.replace(curpos, wordsize, repstr);
}
}
}
}
Teach me how to do this the way that a C++ purist would do it.