如何用标准c++库替换字符串的一部分?

QString s("hello $name");  // Example using Qt.
s.replace("$name", "Somename");

当前回答

在c++ 11中,你可以像这样使用std::regex:

#include <regex>
...
std::string string("hello $name");
string = std::regex_replace(string, std::regex("\\$name"), "Somename");

对于转义字符,需要使用双反斜杠。

其他回答

我自己的实现,考虑到字符串只需要调整一次大小,然后替换就可以发生。

template <typename T>
std::basic_string<T> replaceAll(const std::basic_string<T>& s, const T* from, const T* to)
{
    auto length = std::char_traits<T>::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;
}

用法可以是这样的:

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

这个用起来可能更好

void replace(string& input, const string& from, const string& to)
{
    auto pos = 0;
    while(true)
    {
        size_t startPosition = input.find(from, pos);
        if(startPosition == string::npos)
            return;
        input.replace(startPosition, from.length(), to);
        pos += to.length();
    }
}

在c++ 11中,你可以像这样使用std::regex:

#include <regex>
...
std::string string("hello $name");
string = std::regex_replace(string, std::regex("\\$name"), "Somename");

对于转义字符,需要使用双反斜杠。

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

您可以将其包装在一个函数中,但这种单行解决方案听起来是可以接受的。 问题是这只会改变第一次出现,您可能想要遍历它,但它也允许您使用相同的令牌(%s)在此字符串中插入几个变量。

那么加速方案呢:

boost::replace_all(value, "token1", "token2");