c++中replace函数用法总结

来源:互联网 发布:淘宝卖家自动核对地址 编辑:程序博客网 时间:2024/05/01 04:47

一、用法一

string& replace (size_t pos, size_t len, const string& str) 用str 替换指定字符串从起始位置pos开始长度为len 的字符

replace(i, j, str);    用str 替换从i 开始的长度为 j 的字符


例子:

#include<iostream>using namespace std;int main(){string line="hello world, i love python!";string s = line.replace(line.find("i"), 1, "haha");cout<<s<<endl;return 0;}

输出



二、用法二

string& replace (const_iterator i1, const_iterator i2, const string& str);

用str替换 迭代器起始位置和结束位置的字符


例子:

#include<iostream>using namespace std;int main(){string line="hello world, i love python!";string s = line.replace(line.begin(), line.begin()+5, "haha");cout<<s<<endl;return 0;}

输出:



三、用法三

string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);

用substr 的指定子串(给定起始位置和长度)替换从指定位置上的字符串


例子:

#include<iostream>using namespace std;int main(){string line="hello world, i love python!";string substr="12345"; string s = line.replace(0, 5, substr, substr.find("2"), 3);cout<<s<<endl;return 0;}

输出:



四、用法四

string& replace (size_t pos, size_t len, size_t n, char c);

用重复n 次的c 字符替换从指定位置 pos 长度为 len 的内容


例子:

#include<iostream>using namespace std;int main(){string line="hello world, i love python!";char substr='1';string s = line.replace(0, 5, 3, substr);cout<<s<<endl;return 0;}


输出:



五、用法五

string& replace (const_iterator i1, const_iterator i2, size_t n, char c)

用重复 n 次的 c 字符替换从指定迭代器位置(从 i1 开始到结束)的内容


例子:

#include<iostream>using namespace std;int main(){string line="hello world, i love python!";char substr='1';string s = line.replace(line.begin(), line.begin()+5, 3, substr);cout<<s<<endl;return 0;}

输出:



0 0
原创粉丝点击