How to find and replace all occurrences of a substring in a string?

前端 未结 7 1423
无人共我
无人共我 2020-12-31 06:49

I need to search a string and edit the formatting of it.

So far I can replace the first occurrence of the string, but I am unable to do so with the next occurrences

7条回答
  •  借酒劲吻你
    2020-12-31 07:24

    It's fairly awkward (and probably not too efficient) to do it in place. I usually use a function along the lines of:

    std::string
    replaceAll( std::string const& original, std::string const& from, std::string const& to )
    {
        std::string results;
        std::string::const_iterator end = original.end();
        std::string::const_iterator current = original.begin();
        std::string::const_iterator next = std::search( current, end, from.begin(), from.end() );
        while ( next != end ) {
            results.append( current, next );
            results.append( to );
            current = next + from.size();
            next = std::search( current, end, from.begin(), from.end() );
        }
        results.append( current, next );
        return results;
    }
    

    Basically, you loop as long as you can find an instance of from, appending the intermediate text and to, and advancing to the next instance of from. At the end, you append any text after the last instance of from.

    (If you're going to do much programming in C++, it's probably a good idea to get used to using iterators, like the above, rather than the special member functions of std::string. Things like the above can be made to work with any of the C++ container types, and for this reason, are more idiomatic.)

提交回复
热议问题