1 std::string替换字符串中所有指定的子字符串

std::string并没有提供类似repalceALL之类的方法,我们只能使用std::string::replace方法逐个替换子字符串。

封装的方法如下:

std::string ReepalceAllString(std::string origin_str, const std::string& be_replaced_str, const std::string& new_replace_str)
{
    std::string result_str = origin_str;
    for (std::string::size_type pos = 0; pos != std::string::npos; pos += new_replace_str.length())
    {
        pos = result_str.find(be_replaced_str, pos);
        if (pos != std::string::npos)
        {
            result_str.replace(pos, be_replaced_str.length(), new_replace_str);
        }
        else
        {
            break;
        }
    }

    return result_str;
}

比如现在要将路径E:\\database\\test\\test2\\test3中的\\全部替换为反斜杠/,示例程序如下:

#include <iostream>
#include <string>

std::string ReepalceAllString(std::string origin_str, const std::string& be_replaced_str, const std::string& new_replace_str)
{
    std::string result_str = origin_str;
    for (std::string::size_type pos = 0; pos != std::string::npos; pos += new_replace_str.length())
    {
        pos = result_str.find(be_replaced_str, pos);
        if (pos != std::string::npos)
        {
            result_str.replace(pos, be_replaced_str.length(), new_replace_str);
        }
        else
        {
            break;
        }
    }

    return result_str;
}

int main()
{
    std::string str = "E:\\database\\test\\test2\\test3";

    std::string strreplace = ReepalceAllString(str, "\\", "/");

    std::cout << "原始字符串:" << str << std::endl;
    std::cout << "替换后字符串:" << strreplace << std::endl;

    return 0;
}

结果:

原始字符串:E:\database\test\test2\test3
替换后字符串:E:/database/test/test2/test3