C++string中replace()函数
-
basic_string& replace(size_type pos, size_type n, const basic_string& str)
-用str替换原串中下标为pos开始数的n个字符。 -
basic_string& replace(iterator first, itrator last, const basic_string& str)
和上面类似。 -
basic_string& replace(size_type pos, size_type n, size_type m, char c)
用m个字符c替换原串中下标为pos开始数的n个字符。 -
basic_string& replace(iterator first, itrator last, size_type m, char c)
和上面类似。 -
basic_string& replace(size_type pos1, size_type n, const basic_string& str, size_type pos2, size_type m)
用str从pos2开始数的m个字符替换原串从pos1开始数的n个字符。
代码:
#include<iostream>
using namespace std;
int main()
{
string str="She study really hard!";
str=str.replace(0,3,"He");//原串从下标为0数的3个字符She用He替换
cout<<str<<endl;
string str1="She study really hard!";
str1=str1.replace(str1.begin(),str1.begin()+3,"He");
cout<<str1<<endl;//原串从下标为0数的3个字符She用He替换
string s="Hello! You are nice!";
char c='h';
s=s.replace(0,6,5,c);//原串从下标为0的6个字符用5个字符h替换
cout<<s<<endl;
string s1="Hello! You are nice!";
char c1='h';
s1=s1.replace(0,6,5,c1);//原串从下标为0的6个字符用5个字符h替换
cout<<s1<<endl;
string str2="Good morning! Enjoy youself!";
string s2="A good evening..";
str2=str2.replace(5,8,s2,7,9);//s2从下标7开始的9个字符来替换s1从下标5开始的8个字符
cout<<str2<<endl;
return 0;
}
运行结果:
永远相信美好🎈