How to replace all occurrences of a character in string?

后端 未结 15 1444
别那么骄傲
别那么骄傲 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);
    }
    

提交回复
热议问题