サブストリングを別のサブストリングC++に置き換えます
ここでは、部分文字列を別の部分文字列に置き換える方法を説明します。文字列のposで始まり、len文字にまたがる部分を置き換えます。
置換関数の構造は次のとおりです。
string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);
パラメータはposです :挿入ポイントです、 str :文字列オブジェクトです。len:消去する文字数に関する情報が含まれています。
アルゴリズム
Step 1: Get the main string, and the string which will be replaced. And the match string Step 2: While the match string is present in the main string: Step 2.1: Replace it with the given string. Step 3: Return the modified string
サンプルコード
#include <iostream>
#include <string>
using namespace std;
int main () {
string base = "this is a test string.";
string str2 = "n example";
string str3 = "sample phrase";
string str4 = "useful.";
string str = base;
str.replace(9,5,str2);
str.replace(19,6,str3,7,6);
str.replace(8,10,"just a");
str.replace(8,6,"a shorty",7);
str.replace(22,1,3,'!');
str.replace(str.begin(),str.end()-3,str3);
str.replace(str.begin(),str.begin()+6,"replace");
str.replace(str.begin()+8,str.begin()+14,"is coolness",7);
str.replace(str.begin()+12,str.end()-4,4,'o');
str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());
cout << str << '\n';
return 0;
} 出力
replace is useful.
-
文字列内のすべてのスペースを「%20」に置き換えるC#プログラム
スペースを含むサンプル文字列があります- str ="Hello World !"; C#のReplace()メソッドを使用して、文字列内のすべてのスペースを「%20」に置き換えます- str2 = str.Replace(" ", "%20"); 例 次のコードを実行して、文字列内のすべてのスペースを「%20」に置き換えることができます。 using System; class Demo { static void Main() { String str, str
-
Pythonで文字列のすべての出現箇所を別の文字列に置き換えるにはどうすればよいですか?
Pyhtonには、文字列クラスでreplaceというメソッドがあります。入力として、置き換える文字列と置き換える文字列を取ります。文字列オブジェクトで呼び出されます。このメソッドを次の方法で呼び出して、すべての「no」を「yes」に置き換えることができます。 >>> 'no one knows how'.replace('no', 'yes') 'yes one kyesws how' >>> "chihuahua".replace("hua", &quo