Replace part of a string with another string

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

    You can use this code for remove subtring and also replace , and also remove extra white space . code :

    #include
    using namespace std ;
    void removeSpaces(string &str)
    {
       
        int n = str.length();
    
        int i = 0, j = -1;
    
        bool spaceFound = false;
    
        while (++j <= n && str[j] == ' ');
    
        while (j <= n)
        {
            if (str[j] != ' ')
            {
              
                if ((str[j] == '.' || str[j] == ',' ||
                     str[j] == '?') && i - 1 >= 0 &&
                     str[i - 1] == ' ')
                    str[i - 1] = str[j++];
    
                else
                    
                    str[i++] = str[j++];
    
                
                spaceFound = false;
            }
            else if (str[j++] == ' ')
            {
                
                if (!spaceFound)
                {
                    str[i++] = ' ';
                    spaceFound = true;
                }
            }
        }
    
        if (i <= 1)
            str.erase(str.begin() + i, str.end());
        else
            str.erase(str.begin() + i - 1, str.end());
    }
    int main()
    {
        string s;
        cin>>s;
        for(int i=s.find("WUB");i>=0;i=s.find("WUB"))
        {
            s.replace(i,3," ");
        }
        removeSpaces(s);
        cout<

提交回复
热议问题