好问题
Good  Question
  • 首 页
  • 问题
    • PHP
    • JAVA
    • CPlusPlus
    • C#
    • SQL
  • 关 于
  • 联 系
如何使用C++把部分字符串替换为其他字符串? 关闭 返回上一级  

如何使用C++把部分字符串替换为其他字符串?
+ 查看更多

发布日期:2018-02-26 14:04
分类:CPlusPlus
浏览次数:105
我想通过c++标准库实现这样:
QString string("hello $name");
string.replace("$name", "Somename");

回答

有一个查询字串的方法string(find),并且有另外一个方法用于替换字符串的指定区域string (replace),你可以结合起来使用:
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'
    }
}
上一篇如何在C++代码/项目中找到内存泄漏的原因?
使用字符串分隔符(标准C ++)解析(拆分)C++中的字符串下一篇
下一篇使用字符串分隔符(标准C ++)解析(拆分)C++中的字符串

最新文章

  • 函数`__construct`用来干嘛的
    发布日期:2018-03-26
  • 通过访客的IP得到他们的地区
    发布日期:2018-03-26
  • 合并两个PHP对象的最好的方法是什么?
    发布日期:2018-03-26
  • 该如何把一该如何把一个对象转化成数组?
    发布日期:2018-03-26
  • 什么是输出缓冲区?
    发布日期:2018-03-26
  • 在PHP中怎么把用逗号分隔的字符串分隔在一个数组里?
    发布日期:2018-03-26
  • 在PHP中使用foreach循环时查找数组的最后一个元素
    发布日期:2018-03-26
关于好问
收集整理一些有用的问题和回答,造福中国的程序旺和IT喵们!
友情链接
起飞页 
相关信息
版权声明
Copyright © 2016 - 2022  苏州卡达网络科技有限公司 备案号:苏ICP备09008221号