How to replace all occurrences of a character in string?

后端 未结 15 1266
别那么骄傲
别那么骄傲 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:21

    Imagine a large binary blob where all 0x00 bytes shall be replaced by "\1\x30" and all 0x01 bytes by "\1\x31" because the transport protocol allows no \0-bytes.

    In cases where:

    • the replacing and the to-replaced string have different lengths,
    • there are many occurences of the to-replaced string within the source string and
    • the source string is large,

    the provided solutions cannot be applied (because they replace only single characters) or have a performance problem, because they would call string::replace several times which generates copies of the size of the blob over and over. (I do not know the boost solution, maybe it is OK from that perspective)

    This one walks along all occurrences in the source string and builds the new string piece by piece once:

    void replaceAll(std::string& source, const std::string& from, const std::string& to)
    {
        std::string newString;
        newString.reserve(source.length());  // avoids a few memory allocations
    
        std::string::size_type lastPos = 0;
        std::string::size_type findPos;
    
        while(std::string::npos != (findPos = source.find(from, lastPos)))
        {
            newString.append(source, lastPos, findPos - lastPos);
            newString += to;
            lastPos = findPos + from.length();
        }
    
        // Care for the rest after last occurrence
        newString += source.substr(lastPos);
    
        source.swap(newString);
    }
    
    0 讨论(0)
  • 2020-11-22 06:25

    I thought I'd toss in the boost solution as well:

    #include <boost/algorithm/string/replace.hpp>
    
    // in place
    std::string in_place = "blah#blah";
    boost::replace_all(in_place, "#", "@");
    
    // copy
    const std::string input = "blah#blah";
    std::string output = boost::replace_all_copy(input, "#", "@");
    
    0 讨论(0)
  • 2020-11-22 06:25

    For simple situations this works pretty well without using any other library then std::string (which is already in use).

    Replace all occurences of character a with character b in some_string:

    for (size_t i = 0; i < some_string.size(); ++i) {
        if (some_string[i] == 'a') {
            some_string.replace(i, 1, "b");
        }
    }
    

    If the string is large or multiple calls to replace is an issue, you can apply the technique mentioned in this answer: https://stackoverflow.com/a/29752943/3622300

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

    std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

    #include <algorithm>
    #include <string>
    
    void some_func() {
      std::string s = "example string";
      std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
    }
    
    0 讨论(0)
  • 2020-11-22 06:27

    Old School :-)

    std::string str = "H:/recursos/audio/youtube/libre/falta/"; 
    
    for (int i = 0; i < str.size(); i++) {
        if (str[i] == '/') {
            str[i] = '\\';
        }
    }
    
    std::cout << str;
    

    Result:

    H:\recursos\audio\youtube\libre\falta\

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

    here's a solution i rolled, in a maximal DRI spirit. it will search sNeedle in sHaystack and replace it by sReplace, nTimes if non 0, else all the sNeedle occurences. it will not search again in the replaced text.

    std::string str_replace(
        std::string sHaystack, std::string sNeedle, std::string sReplace, 
        size_t nTimes=0)
    {
        size_t found = 0, pos = 0, c = 0;
        size_t len = sNeedle.size();
        size_t replen = sReplace.size();
        std::string input(sHaystack);
    
        do {
            found = input.find(sNeedle, pos);
            if (found == std::string::npos) {
                break;
            }
            input.replace(found, len, sReplace);
            pos = found + replen;
            ++c;
        } while(!nTimes || c < nTimes);
    
        return input;
    }
    
    0 讨论(0)
提交回复
热议问题