C++中的string类提供了replace()函数,用于替换字符串中的子串。其函数原型如下:
string replace (size_t pos, size_t len, const string& str);
其中,pos表示要替换的子串在原字符串中的起始位置,len表示要替换的子串的长度,str表示用来替换的字符串。
replace()函数的使用方法非常简单,只需要传入要替换的子串的位置、长度和替换字符串即可。下面是一个示例:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "hello world";
str.replace(0, 5, "hi");
cout << str << endl; // 输出:hi world
return 0;
}
在上面的示例中,将字符串中的"hello"替换为"hi",得到了"hi world"这个新的字符串。