Replace part of a string with another string

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

    If you want to do it quickly you can use a two scan approach. Pseudo code:

    1. first parse. find how many matching chars.
    2. expand the length of the string.
    3. second parse. Start from the end of the string when we get a match we replace, else we just copy the chars from the first string.

    I am not sure if this can be optimized to an in-place algo.

    And a C++11 code example but I only search for one char.

    #include 
    #include 
    #include 
    using namespace std;
    
    void ReplaceString(string& subject, char search, const string& replace)
    {   
        size_t initSize = subject.size();
        int count = 0;
        for (auto c : subject) { 
            if (c == search) ++count;
        }
    
        size_t idx = subject.size()-1 + count * replace.size()-1;
        subject.resize(idx + 1, '\0');
    
        string reverseReplace{ replace };
        reverse(reverseReplace.begin(), reverseReplace.end());  
    
        char *end_ptr = &subject[initSize - 1];
        while (end_ptr >= &subject[0])
        {
            if (*end_ptr == search) {
                for (auto c : reverseReplace) {
                    subject[idx - 1] = c;
                    --idx;              
                }           
            }
            else {
                subject[idx - 1] = *end_ptr;
                --idx;
            }
            --end_ptr;
        }
    }
    
    int main()
    {
        string s{ "Mr John Smith" };
        ReplaceString(s, ' ', "%20");
        cout << s << "\n";
    
    }
    

提交回复
热议问题