无涯教程-进程 - string& replace(int pos,int len,string& str)函数

43 阅读2分钟

此函数替换从字符位置pos开始并跨越len个字符的字符串部分。

replace - 语法

str1.replace(pos,len,str2);

replace - 参数

  • str          -  str是一个字符串对象,其值将被复制到另一个字符串对象中。
  • pos         -  pos定义要替换其字符的位置。
  • len           -  要由另一个字符串对象替换的字符数。
  • subpos   - 它定义了要复制到另一个对象的字符串对象的第一个字符的位置。
  • sublen    -  要复制到另一个字符串对象中的字符串对象的字符数。
  • n               - 要复制到另一个字符串对象中的字符数。

replace - 返回值

此函数不返回任何值。

replace - 例子1

第一个示例显示如何通过使用位置和长度作为参数来替换给定的字符串。

#include<iostream>
using namespace std;
int  main()
{
string str1 = "This is C language";
string str2 = "C++";
cout << "Before replacement, string is :"<<str1<<
;
str1.replace(8,1,str2); 
cout << "After replacement, string is :"<<str1<<
;
return 0;
} 

输出:

Before replacement , string is This is C language
After replacement, string is This is C++ language

replace - 例子2

第二个示例显示了如何使用要复制到另一个字符串对象中的字符串的位置和长度替换给定的字符串。

#include<iostream>
using namespace std;
int main()
{
string str1 ="This is C language"
 string str3= "java language";
cout <<"Before replacement, String is "<<str1<<
;
str1.replace(8,1,str3,0,4); 
cout<<"After  replacement,String is "<<str1<<
;
return 0;
} 

输出:

Before replacement, String is This is C language
After replacement, String is This is java language

replace - 例子3

第三个示例显示如何通过使用字符串和要复制的字符数作为参数来替换字符串。

#include<iostream>
using namespace std;
int main()
{
string str1="This is C language";
cout<<"Before replacement,string is"<<str1<<
;
str1.replace(8,1,"C##",2); 
cout<<"After replacement,string is"<<str1;
return 0;
} 

输出:

Before replacement,string is This is C language
After replacement,string is This is C# language

参考链接

www.learnfk.com/c++/cpp-str…