How to replace all occurrences of a character in string?

后端 未结 15 1264
别那么骄傲
别那么骄傲 2020-11-22 05:54

What is the effective way to replace all occurrences of a character with another character in std::string?

相关标签:
15条回答
  • 2020-11-22 06:09

    For completeness, here's how to do it with std::regex.

    #include <regex>
    #include <string>
    
    int main()
    {
        const std::string s = "example string";
        const std::string r = std::regex_replace(s, std::regex("x"), "y");
    }
    
    0 讨论(0)
  • 2020-11-22 06:10

    The question is centered on character replacement, but, as I found this page very useful (especially Konrad's remark), I'd like to share this more generalized implementation, which allows to deal with substrings as well:

    std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
        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(); // Handles case where 'to' is a substring of 'from'
        }
        return str;
    }
    

    Usage:

    std::cout << ReplaceAll(string("Number Of Beans"), std::string(" "), std::string("_")) << std::endl;
    std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("X")) << std::endl;
    std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("h")) << std::endl;
    

    Outputs:

    Number_Of_Beans

    XXjXugtXty

    hhjhugthty


    EDIT:

    The above can be implemented in a more suitable way, in case performances are of your concern, by returning nothing (void) and performing the changes directly on the string str given as argument, passed by address instead of by value. This would avoid useless and costly copy of the original string, while returning the result. Your call, then...

    Code :

    static inline void ReplaceAll2(std::string &str, const std::string& from, const std::string& to)
    {
        // Same inner code...
        // No return statement
    }
    

    Hope this will be helpful for some others...

    0 讨论(0)
  • 2020-11-22 06:10

    As Kirill suggested, either use the replace method or iterate along the string replacing each char independently.

    Alternatively you can use the find method or find_first_of depending on what you need to do. None of these solutions will do the job in one go, but with a few extra lines of code you ought to make them work for you. :-)

    0 讨论(0)
  • 2020-11-22 06:13

    If you're looking to replace more than a single character, and are dealing only with std::string, then this snippet would work, replacing sNeedle in sHaystack with sReplace, and sNeedle and sReplace do not need to be the same size. This routine uses the while loop to replace all occurrences, rather than just the first one found from left to right.

    while(sHaystack.find(sNeedle) != std::string::npos) {
      sHaystack.replace(sHaystack.find(sNeedle),sNeedle.size(),sReplace);
    }
    
    0 讨论(0)
  • 2020-11-22 06:13

    If you're willing to use std::strings, you can use this sample-app's strsub function as-is, or update it if you want it to take a different type or set of parameters to achieve roughly the same goal. Basically, it uses the properties and functionalities of std::string to quickly erase the matching set of characters, and insert the desired characters directly within the std::string. Every time it does this replacement operation, the offset updates if it can still find matching chars to replace, and if it can't due to nothing more to replace, it returns the string in its state from the last update.

    #include <iostream>
    #include <string>
    
    std::string strsub(std::string stringToModify,
                       std::string charsToReplace,
                       std::string replacementChars);
    
    int main()
    {
        std::string silly_typos = "annoiiyyyng syyyllii tiipos.";
    
        std::cout << "Look at these " << silly_typos << std::endl;
        silly_typos = strsub(silly_typos, "yyy", "i");
        std::cout << "After a little elbow-grease, a few less " << silly_typos << std::endl;
        silly_typos = strsub(silly_typos, "ii", "y");
    
        std::cout << "There, no more " << silly_typos << std::endl;
        return 0;
    }
    
    std::string strsub(std::string stringToModify,
                       std::string charsToReplace,
                       std::string replacementChars)
    {
        std::string this_string = stringToModify;
    
        std::size_t this_occurrence = this_string.find(charsToReplace);
        while (this_occurrence != std::string::npos)
        {
            this_string.erase(this_occurrence, charsToReplace.size());
            this_string.insert(this_occurrence, replacementChars);
            this_occurrence = this_string.find(charsToReplace,
                                               this_occurrence + replacementChars.size());
        }
    
        return this_string;
    }
    

    If you don't want to rely on using std::strings as your parameters so you can pass in C-style strings instead, you can see the updated sample below:

    #include <iostream>
    #include <string>
    
    std::string strsub(const char * stringToModify,
                       const char * charsToReplace,
                       const char * replacementChars,
                       uint64_t sizeOfCharsToReplace,
                       uint64_t sizeOfReplacementChars);
    
    int main()
    {
        std::string silly_typos = "annoiiyyyng syyyllii tiipos.";
    
        std::cout << "Look at these " << silly_typos << std::endl;
        silly_typos = strsub(silly_typos.c_str(), "yyy", "i", 3, 1);
        std::cout << "After a little elbow-grease, a few less " << silly_typos << std::endl;
        silly_typos = strsub(silly_typos.c_str(), "ii", "y", 2, 1);
    
        std::cout << "There, no more " << silly_typos << std::endl;
        return 0;
    }
    
    std::string strsub(const char * stringToModify,
                       const char * charsToReplace,
                       const char * replacementChars,
                       uint64_t sizeOfCharsToReplace,
                       uint64_t sizeOfReplacementChars)
    {
        std::string this_string = stringToModify;
    
        std::size_t this_occurrence = this_string.find(charsToReplace);
        while (this_occurrence != std::string::npos)
        {
            this_string.erase(this_occurrence, sizeOfCharsToReplace);
            this_string.insert(this_occurrence, replacementChars);
            this_occurrence = this_string.find(charsToReplace,
                this_occurrence + sizeOfReplacementChars);
        }
    
        return this_string;
    }
    
    0 讨论(0)
  • 2020-11-22 06:19
    #include <iostream>
    #include <string>
    using namespace std;
    // Replace function..
    string replace(string word, string target, string replacement){
        int len, loop=0;
        string nword="", let;
        len=word.length();
        len--;
        while(loop<=len){
            let=word.substr(loop, 1);
            if(let==target){
                nword=nword+replacement;
            }else{
                nword=nword+let;
            }
            loop++;
        }
        return nword;
    
    }
    //Main..
    int main() {
      string word;
      cout<<"Enter Word: ";
      cin>>word;
      cout<<replace(word, "x", "y")<<endl;
      return 0;
    }
    
    0 讨论(0)
提交回复
热议问题