关于replace的问题

hexuan1982 2008-03-05 09:56:53
请问C++中有replace这个系统函数吗?请教下面代码中的replace里每个参数的含义。

while((pos = str.find("{num:1}")) != string::npos)
{
str.replace(pos, 7, szNumber, 8, 1);
}
...全文
49 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Chappell 2008-03-05
  • 打赏
  • 举报
回复
(*^__^*) 嘻嘻……
Chappell 2008-03-05
  • 打赏
  • 举报
回复

#include <string>
#include <iostream>

using namespace std;

string& replace_all(string& str,const string& old_value,const string& new_value)
{
while(true)
{
string::size_type pos(0);
if( (pos=str.find(old_value))!=string::npos )
str.replace(pos,old_value.length(),new_value);
else break;
}
return str;
}

string& replace_all_distinct(string& str,const string& old_value,const string& new_value)
{
for(string::size_type pos(0); pos!=string::npos; pos+=new_value.length()) {
if( (pos=str.find(old_value,pos))!=string::npos )
str.replace(pos,old_value.length(),new_value);
else break;
}
return str;
}

int main()
{
cout << replace_all(string("12212"),"12","21") << endl;
cout << replace_all_distinct(string("12212"),"12","21") << endl;
}

//output:
//22211
//21221
Supper_Jerry 2008-03-05
  • 打赏
  • 举报
回复
楼主,结贴吧。
Supper_Jerry 2008-03-05
  • 打赏
  • 举报
回复
str.replace(pos, 7, szNumber, 8, 1);
pos表示需要替换的起始位置,也就是{num:1}的位置
7表示替换7个元素,{num:1}刚好7个
szNumber表示用szNumber中的字符串替换
8表示szNumber第8为开始
1表示用1个元素来替换
Supper_Jerry 2008-03-05
  • 打赏
  • 举报
回复
basic_string& replace(size_type p0, size_type n0,
const basic_string& str, size_type pos, size_type n);
Each member function replaces up to n0 elements of the controlled sequence beginning with position p0, or the elements of the controlled sequence beginning with the one pointed to by first, up to but not including last. The replacement is the operand sequence specified by the remaining operands. The function then returns *this.

p0303230 2008-03-05
  • 打赏
  • 举报
回复
http://topic.csdn.net/t/20060721/14/4895939.html
p0303230 2008-03-05
  • 打赏
  • 举报
回复
Examines   each   element   in   a   range   and   replaces   it   if   it   matches   a   specified   value.   
template<class ForwardIterator, class Type>
void replace(
ForwardIterator _First,
ForwardIterator _Last,
const Type& _OldVal,
const Type& _NewVal
);
_First
A forward iterator pointing to the position of the first element in the range from which elements are being replaced.

_Last
A forward iterator pointing to the position one past the final element in the range from which elements are being replaced.

_OldVal
The old value of the elements being replaced.

_NewVal
The new value being assigned to the elements with the old value.

64,849

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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