登录 用户中心() [退出] 后台管理 注册 |
热门搜索: |
您的位置:首页 >> 马上代码 >> 马上代码 >> 主题: C++常用函数 -- 字符串替换 |
标题 | C++常用函数 -- 字符串替换 |
clq |
浏览(1191)
2006-02-05 10:39:37 发表
编辑
关键字: 这是我常用的一个函数,里面用到了stl本身的replace函数.注意stl的replace函数在孟岩译的那本<C++标准库>中是表述有错误的,它的第2个参数并不是end[终止位置],而是n[要替换的字符数],我是在老得不到正确结果的情况下参考了BS的<C++程序设计语言特别版>后才发现的这个错误.结合我以前使用<C++标准库>这本书的经验,似乎它错误的地方还真不少.并不象它序言中说的,什么多少年中都没有一本类似的书超过它云云... //替换字符串 std::string str_replace(const std::string s, const std::string old_s, const std::string new_s) { size_t pos = 0; std::string r = s; while(true) { pos = r.find(old_s, pos); if (pos == std::string::npos) break; //c++的replace是与其他语言有所不同的 //r.replace(pos, pos + old_s.length(), new_s); //注意第二个参数是字数 r.replace(pos, old_s.length(), new_s); pos += new_s.length();//查找位置要向下移 } return r; } |
Copyright © 2005-2012 CLQ工作室, All Rights Reserved CLQ工作室 版权所有 |