C++ replace函数

来源:互联网 发布:convertio for mac 编辑:程序博客网 时间:2024/06/06 05:44




#include<stdio.h>#include<string>#include<iostream>using namespace std; string line="it*is*a string!";  /*用法一: 用str替换指定字符串从起始位置pos开始长为len的字符串 *string& replace (size_t pos, size_t len, const string& str);  */void string_1(string s1){cout<<"method_1"<<endl; s1=s1.replace(s1.find("*"),1,"/");cout<<s1<<endl;}   /*用法二: 用str替换迭代器起始位置和结束位置的字符  *string& replace (const_iterator i1, const_iterator i2, const string& str);  */void string_2(string s1){cout<<"method_2"<<endl; s1=s1.replace(s1.begin(),s1.begin()+6,"-");cout<<s1<<endl;}   /*用法三: 用str的指定字串(给定起始位置和长度)替换指定位置 *string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);  */void string_3(string s1){cout<<"method_3"<<endl; string  str1="885988";s1=s1.replace(0,5,str1,str1.find("5"),3);cout<<s1<<endl;}    /*用法四:string转char*时编译器可能会报出警告,不建议这样做  *用str替换从指定位置0开始长度为5的字符串  *string& replace(size_t pos, size_t len, const char* s);   */void string_4(string s1){cout<<"method_4"<<endl; char *str="12345"; s1=s1.replace(0,1,str);cout<<s1<<endl;}    /*用法五:string转char*时编译器可能会报出警告,不建议这样做  *用str替换从指定迭代器位置的字符串  *string& replace (const_iterator i1, const_iterator i2, const char* s);  */ void string_5(string s1){cout<<"method_5"<<endl; char *str="12345"; s1=s1.replace(s1.begin(),s1.begin()+9,str);cout<<s1<<endl;}  /*用法六:  *用重复n次的c字符替换从指定位置pos长度为len的内容  *string& replace (size_t pos, size_t len, size_t n, char c);  */  void string_6(string s1){cout<<"method_6"<<endl; char str='2'; s1=s1.replace(0,9,2,str);//用重复2次的str字符替换从指定位置0长度为9的内容  cout<<s1<<endl;} /*用法七:  *用重复n次的c字符替换从指定迭代器位置(从i1开始到结束)的内容  *string& replace (const_iterator i1, const_iterator i2, size_t n, char c);  */  void string_7(string s1){cout<<"method_7"<<endl; char str='2'; s1=s1.replace(s1.begin(),s1.begin()+9,3,str);//用重复2次的str字符替换从指定位置0长度为9的内容  cout<<s1<<endl;}    int main(){  string_1(line); string_2(line); string_3(line); string_4(line); string_5(line);string_6(line); string_7(line);  }


原创粉丝点击