Replace part of a string with another string

前端 未结 15 2657
终归单人心
终归单人心 2020-11-22 02:54

Is it possible in C++ to replace part of a string with another string?

Basically, I would like to do this:

QString string(\"hello $name\");
string.re         


        
15条回答
  •  感动是毒
    2020-11-22 03:44

    I use generally this:

    std::string& replace(std::string& s, const std::string& from, const std::string& to)
    {
        if(!from.empty())
            for(size_t pos = 0; (pos = s.find(from, pos)) != std::string::npos; pos += to.size())
                s.replace(pos, from.size(), to);
        return s;
    }
    

    It repeatedly calls std::string::find() to locate other occurrences of the searched for string until std::string::find() doesn't find anything. Because std::string::find() returns the position of the match we don't have the problem of invalidating iterators.

提交回复
热议问题