使用另一個子字串替換 C++ 子字串


這裡我們將瞭解如何使用另一個子字串替換子字串。替換字串中從字元位置 pos 開始且跨越 len 字元的部分。

replace 函式的結構如下

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.

更新於: 30-Jul-2019

2K+ 人次觀看

開啟您的職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.