-3

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.

Sunil Devre
  • 374
  • 1
  • 15
user3178285
  • 151
  • 2
  • 7
  • Just saying. I believe this question belongs at https://codereview.stackexchange.com/ – Crystal Meth Mar 16 '14 at 06:33
  • 1
    Possible duplicate of http://stackoverflow.com/questions/3418231/replace-part-of-a-string-with-another-string – Rad1 Mar 16 '14 at 06:35
  • [Replace part of a string with another string](http://stackoverflow.com/q/3418231/445976), [Replace substring with another substring C++](http://stackoverflow.com/q/4643512/445976), [How do I replace all instances of of a string with another string?](http://stackoverflow.com/q/5343190/445976) – Blastfurnace Mar 20 '14 at 07:10

1 Answers1

0
for( auto pos = str.find( word ); pos != std::string::npos; pos = str.find( word ) )
{
    str.replace( str.begin() + pos, str.begin() + pos + word.size(), word.size(),'*' );
}

We find the first appearance of the word we want replaced. We then replace it. We do this until there are no more appearances, as they have all been replaced.

Ben
  • 1,816
  • 1
  • 20
  • 29