c++中replace函数用法总结

一、用法一

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;
}

输出:



C++的`replace`函数可以用来将字符串的指定字符或子串替换为另一个字符或子串。其用法如下: ```c++ string replace (size_t pos, size_t len, const string& str); string replace (const_iterator i1, const_iterator i2, const string& str); string replace (size_t pos, size_t len, const char* s); string replace (const_iterator i1, const_iterator i2, const char* s); string replace (size_t pos, size_t len, size_t n, char c); string replace (const_iterator i1, const_iterator i2, size_t n, char c); ``` 其,`pos`表示要替换的起始位置,`len`表示要替换的长度,`str`或`s`表示替换成的新字符串或字符,`i1`和`i2`表示一个迭代器范围,`n`表示要替换成的字符的个数,`c`表示要替换成的字符。 例如,要将字符串`s`从第2个字符开始的3个字符替换为字符串`new_str`,可以这样写: ```c++ string s = "hello world"; string new_str = "hi"; s.replace(1, 3, new_str); ``` 这样`s`的值就变成了`hhi world`。 另外,如果要将字符串所有的某个字符或子串都替换为另一个字符或子串,可以使用`std::replace`算法,其用法如下: ```c++ std::replace(str.begin(), str.end(), old_char, new_char); // 将字符 old_char 替换为 new_char std::replace(str.begin(), str.end(), old_str, new_str); // 将子串 old_str 替换为 new_str ``` 其,`str`是要替换的字符串,`old_char`和`new_char`分别表示要替换的字符和替换后的字符,`old_str`和`new_str`分别表示要替换的子串和替换后的子串。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值