用另一个字符串替换一个字符串的一部分

2022-01-30 00:00:00 string replace substring c++ std

在 C++ 中是否可以用另一个字符串替换部分字符串?

Is it possible in C++ to replace part of a string with another string?

基本上,我想这样做:

QString string("hello $name");
string.replace("$name", "Somename");

但我想使用标准 C++ 库.

But I would like to use the Standard C++ libraries.

推荐答案

有一个函数可以在字符串中查找子字符串 (find),以及用另一个字符串替换字符串中特定范围的函数 (replace),因此您可以将它们组合起来以获得您想要的效果:

There's a function to find a substring within a string (find), and a function to replace a particular range in a string with another string (replace), so you can combine those to get the effect you want:

bool replace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos)
        return false;
    str.replace(start_pos, from.length(), to);
    return true;
}

std::string string("hello $name");
replace(string, "$name", "Somename");

<小时>

在回复评论时,我认为 replaceAll 可能看起来像这样:

void replaceAll(std::string& str, const std::string& from, const std::string& to) {
    if(from.empty())
        return;
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
    }
}

相关文章