Replace part of a string with another string

前端 未结 15 2352
终归单人心
终归单人心 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:41

    There's a function to find a substring within a string (find), and a function to replace a particular range in a string with another string (replace), so you can combine those to get the effect you want:

    bool replace(std::string& str, const std::string& from, const std::string& to) {
        size_t start_pos = str.find(from);
        if(start_pos == std::string::npos)
            return false;
        str.replace(start_pos, from.length(), to);
        return true;
    }
    
    std::string string("hello $name");
    replace(string, "$name", "Somename");
    

    In response to a comment, I think replaceAll would probably look something like this:

    void replaceAll(std::string& str, const std::string& from, const std::string& to) {
        if(from.empty())
            return;
        size_t start_pos = 0;
        while((start_pos = str.find(from, start_pos)) != std::string::npos) {
            str.replace(start_pos, from.length(), to);
            start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
        }
    }
    

提交回复
热议问题