赞
踩
replace函数包含于头文件#include<string>中。
泛型算法replace把队列中与给定值相等的所有值替换为另一个值,整个队列都被扫描,即此算法的各个版本都在线性时间内执行———其复杂度为O(n)。
即replace的执行要遍历由区间[frist,last)限定的整个队列,以把old_value替换成new_value。
下面说下replace()的九种用法:(编译软件dev5.4.0)
代码如下:
- #include<iostream>
- #include<string>
- using namespace std;
- int main()
- {
- string str = "he is@ a@ good boy";
- str=str.replace(str.find("a"),2,"#"); //从第一个a位置开始的两个字符替换成#
- cout<<str<<endl;
- return 0;
- }
即将 a@ 替换为 # 。
结果如下:
- #include<iostream>
- #include<string>
- using namespace std;
- int main()
- {
- string str = "he is@ a@ good boy";
- str=str.replace(str.begin(),str.begin()+5,"#"); //用#替换从begin位置开始的5个字符
- cout<<str<<endl;
- return 0;
- }
结果如下:
- #include<iostream>
- #include<string>
- using namespace std;
- int main()
- {
- string str = "he is@ a@ good boy";
- string substr = "12345";
- str=str.replace(0,5,substr,substr.find("1"),4); //用substr的指定字符串替换str指定字符串
- cout << str << endl;
- return 0;
- }
0:起始位置;5:长度; 4: substr的指定长度。
结果如下:
代码如下:
- #include<iostream>
- #include<string>
- using namespace std;
- int main()
- {
- string str = "he is@ a@ good boy";
- char * str1 = "12345";
- str=str.replace(0,5,str1); //用str替换从指定位置开始长度为5的字符串
- cout<<str<<endl;
- return 0;
- }
结果如下:
代码如下:
- #include<iostream>
- #include<string>
- using namespace std;
- int main()
- {
- string str = "he is@ a@ good boy";
- char * str1 = "12345";
- str=str.replace(str.begin(),str.begin()+6,str1); //用str替换从指定迭代器位置的字符串
- cout<<str<<endl;
- return 0;
- }
结果如下:
代码如下:
- #include<iostream>
- #include<string>
- using namespace std;
- int main()
- {
- string str = "he is@ a@ good boy";
- char * str1 = "12345";
- str=str.replace(0,6,str1,4); //用str1的前4个字符串替换从位置0~6的字符串
- cout<<str<<endl;
- return 0;
- }
结果如下:
代码如下:
- #include<iostream>
- #include<string>
- using namespace std;
- int main()
- {
- string str = "he is@ a@ good boy";
- char * str1 = "12345";
- str = str.replace(str.begin(),str.begin()+6,str1,4); //用str1的前4个字符串替换从位置0~6的字符串
- cout<<str<<endl;
- return 0;
- }
结果如下:
代码如下:
- #include<iostream>
- #include<string>
- using namespace std;
- int main()
- {
- string str = "he is@ a@ good boy";
- char str1 = '#';
- str = str.replace(0,6,3,str1); //用重复3次的str1字符替换的替换从位置0~6的字符串
- cout<<str<<endl;
- return 0;
- }
结果如下:
代码如下:
- #include<iostream>
- #include<string>
- using namespace std;
- int main()
- {
- string str = "he is@ a@ good boy";
- char str1 = '#';
- str = str.replace(str.begin(),str.begin()+6,3,str1); //用重复3次的str1字符替换的替换从指定迭代器位置的内容
- cout<<str<<endl;
- return 0;
- }
结果如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。