◎◎怎样用string.replace()完成字符串的替换功能呢?

ddmor 2004-01-18 08:33:42
比如我想把字符串"abcdefg"中的"def"替换为"yxz",那该怎么办呢?
我用string.replace()老是出错啊。
...全文
365 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
梦想成了相扑 2004-08-25
  • 打赏
  • 举报
回复
试试这个函数。更多精彩,尽在:http://blog.csdn.net/mxclxp/archive/2004/08/25/84818.aspx(原创!!)

//////////////////////////////////////////////////////////////////////////
/*
* 功能: 把 "原始串" 中所有的 "替换源串" 替换成 "替换目的串",返回替换完
的结果。
* 意义: 此功能解决了 std::string 中替换功能的单一,方便了编程。
*/
//////////////////////////////////////////////////////////////////////////
std::string stringReplace(const std::string& input, // 原始串
const std::string& find, // 替换源串
const std::string& replaceWith) // 替换目的串
{
std::string strOut(input);
int curPos = 0;

int pos;
while((pos = strOut.find(find, curPos)) != -1)
{
strOut.replace(pos, find.size(), replaceWith); // 一次替换
curPos = pos + replaceWith.size(); // 防止循环替换!!
}

return strOut;
}

donkey829 2004-01-19
  • 打赏
  • 举报
回复
agree to
merlinran 2004-01-18
  • 打赏
  • 举报
回复
为了替换,你必须先找到要替换的串的位置。
string s("abcdefg");
string::size_type sz = s.find("def");

// 验证确实找到了
if (sz != string::npos)
{
s.replace(sz, 3, "yxz");
}

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧