1.按照位置进行替换
string的成员函数replace可以满足这种需求,其变体有很多种,请参考官方文档,以下列举常用的两种:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "hello world";
s.replace(s.begin(), s.begin() + 5, "hi"); //通过迭代器,指示被替换的位置
cout<<s<<endl;
s.replace(0, 2, "hello"); //通过索引及长度,指示被替换的位置
cout<<s<<endl;
return 0;
}
运行程序输出:
hi world
hello world
2.替换指定的字符
如果需要将string中所有指定的字符全部替换,如果使用成员函数replace比较的麻烦,这时可以使用STL的replace模板:
template< class ForwardIt, class T >
void replace( ForwardIt first, ForwardIt last,
const T& old_value, const T& new_value );
</