C++ の文字列クラスは、文字列内の部分文字列を置換するための 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」が取得されます。