Replace part of a string with another string

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

    I'm just now learning C++, but editing some of the code previously posted, I'd probably use something like this. This gives you the flexibility to replace 1 or multiple instances, and also lets you specify the start point.

    using namespace std;
    
    // returns number of replacements made in string
    long strReplace(string& str, const string& from, const string& to, size_t start = 0, long count = -1) {
        if (from.empty()) return 0;
    
        size_t startpos = str.find(from, start);
        long replaceCount = 0;
    
        while (startpos != string::npos){
            str.replace(startpos, from.length(), to);
            startpos += to.length();
            replaceCount++;
    
            if (count > 0 && replaceCount >= count) break;
            startpos = str.find(from, startpos);
        }
    
        return replaceCount;
    }
    

提交回复
热议问题