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

前端 未结 7 1488
无人共我
无人共我 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:12

    If ever the strings you need to invert are not of the same size:

    void            Replace::replace(std::string & str, std::string const & s1, std::string const & s2)
    {
        size_t      pos;
    
        pos = 0;
        while ((pos = str.find(s1, pos)) != std::string::npos)
        {
            str.erase(pos, s1.length());
            str.insert(pos, s2);
            pos += s2.length();
        }
        return ;
    }
    

提交回复
热议问题