C++ String replace()
C++ String replace()
此函数替换从字符位置pos开始并跨越len个字符的字符串部分。
语法
考虑两个字符串str1和str2、语法为:
str1.replace(pos,len,str2);
参数
str: str是一个字符串对象,其值将被复制到另一个字符串对象中。
pos: pos定义要替换其字符的位置。
len: 要由另一个字符串对象替换的字符数。
subpos: 它定义了要复制到另一个对象的字符串对象的第一个字符的位置。
sublen: 要复制到另一个字符串对象中的字符串对象的字符数。
n: 要复制到另一个字符串对象中的字符数。
返回值
此函数不返回任何值。
示例1
第一个示例显示如何通过使用位置和长度作为参数来替换给定的字符串。
#include<iostream>
using namespace std;
int main()
{
string str1 = "this is C language";
string str2 = "C++";
cout << "Before replacement, string is :"<<str1<<'\n';
str1.replace(8,1,str2);
cout << "After replacement, string is :"<<str1<<'\n';
return 0;
}
输出:
Before replacement , string is this is C language
After replacement, string is this is C++ language
示例2
第二个示例演示如何使用要复制到另一个字符串对象中的字符串的位置和长度替换给定的字符串。
#include<iostream>
using namespace std;
int main()
{
string str1 ="this is C language"
string str3= "java language";
cout <<"Before replacement, String is "<<str1<<'\n';
str1.replace(8,1,str3,0,4);
cout<<"After replacement,String is "<<str1<<'\n';
return 0;
}
输出:
Before replacement, String is this is C language
After replacement, String is this is java language
示例3
第三个示例演示如何通过使用字符串和要复制的字符数作为参数来替换字符串。
#include<iostream>
using namespace std;
int main()
{
string str1="this is C language";
cout<<"Before replacement,string is"<<str1<<'\n';
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