用另一个字符串替换部分字符串 [英] Replace part of a string with another string

查看:51
本文介绍了用另一个字符串替换部分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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'
    }
}

这篇关于用另一个字符串替换部分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆