Replace part of a string with another string

前端 未结 15 2305
终归单人心
终归单人心 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<bits/stdc++.h>
    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<<s<<endl;
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 03:34

    To have the new string returned use this:

    std::string ReplaceString(std::string subject, const std::string& search,
                              const std::string& replace) {
        size_t pos = 0;
        while ((pos = subject.find(search, pos)) != std::string::npos) {
             subject.replace(pos, search.length(), replace);
             pos += replace.length();
        }
        return subject;
    }
    

    If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:

    void ReplaceStringInPlace(std::string& subject, const std::string& search,
                              const std::string& replace) {
        size_t pos = 0;
        while ((pos = subject.find(search, pos)) != std::string::npos) {
             subject.replace(pos, search.length(), replace);
             pos += replace.length();
        }
    }
    

    Tests:

    std::string input = "abc abc def";
    std::cout << "Input string: " << input << std::endl;
    
    std::cout << "ReplaceString() return value: " 
              << ReplaceString(input, "bc", "!!") << std::endl;
    std::cout << "ReplaceString() input string not modified: " 
              << input << std::endl;
    
    ReplaceStringInPlace(input, "bc", "??");
    std::cout << "ReplaceStringInPlace() input string modified: " 
              << input << std::endl;
    

    Output:

    Input string: abc abc def
    ReplaceString() return value: a!! a!! def
    ReplaceString() input string not modified: abc abc def
    ReplaceStringInPlace() input string modified: a?? a?? def
    
    0 讨论(0)
  • 2020-11-22 03:36
    std::string replace(std::string base, const std::string from, const std::string to) {
        std::string SecureCopy = base;
    
        for (size_t start_pos = SecureCopy.find(from); start_pos != std::string::npos; start_pos = SecureCopy.find(from,start_pos))
        {
            SecureCopy.replace(start_pos, from.length(), to);
        }
    
        return SecureCopy;
    }
    
    0 讨论(0)
  • 2020-11-22 03:38

    This could be even better to use

    void replace(string& input, const string& from, const string& to)
    {
        while(true)
        {
            size_t startPosition = input.find(from);
            if(startPosition == string::npos)
                break;
            input.replace(startPosition, from.length(), to);
        }
    }
    
    0 讨论(0)
  • 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'
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:41

    This sounds like an option

    string.replace(string.find("%s"), string("%s").size(), "Something");

    You could wrap this in a function but this one-line solution sounds acceptable. The problem is that this will change the first occurence only, you might want to loop over it, but it also allows you to insert several variables into this string with the same token (%s)

    0 讨论(0)
提交回复
热议问题