Replace part of a string with another string

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

    My own implementation, taking into account that string needs to be resized only once, then replace can happen.

    template 
    std::basic_string replaceAll(const std::basic_string& s, const T* from, const T* to)
    {
        auto length = std::char_traits::length;
        size_t toLen = length(to), fromLen = length(from), delta = toLen - fromLen;
        bool pass = false;
        std::string ns = s;
    
        size_t newLen = ns.length();
    
        for (bool estimate : { true, false })
        {
            size_t pos = 0;
    
            for (; (pos = ns.find(from, pos)) != std::string::npos; pos++)
            {
                if (estimate)
                {
                    newLen += delta;
                    pos += fromLen;
                }
                else
                {
                    ns.replace(pos, fromLen, to);
                    pos += delta;
                }
            }
    
            if (estimate)
                ns.resize(newLen);
        }
    
        return ns;
    }
    

    Usage could be for example like this:

    std::string dirSuite = replaceAll(replaceAll(relPath.parent_path().u8string(), "\\", "/"), ":", "");
    

提交回复
热议问题