ที่นี่เราจะดูวิธีแทนที่สตริงย่อยด้วยสตริงย่อยอีกตัวหนึ่ง ฟังก์ชันนี้จะแทนที่ส่วนของสตริงที่เริ่มต้นที่ตำแหน่ง pos และมีความยาว len ตัวอักษร
โครงสร้างของฟังก์ชัน replace เหมือนด้านล่าง:
string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);
พารามิเตอร์คือ pos: จุดเริ่มต้นของการแทนที่ str: อ็อบเจ็กต์สตริง len: จำนวนตัวอักษรที่จะลบ
อัลกอริทึม
ขั้นตอน 1: รับสตริงหลัก สตริงที่จะถูกแทนที่ และสตริงที่ตรงกัน
ขั้นตอน 2: ในขณะที่สตริงที่ตรงกันยังอยู่ในสตริงหลัก:
ขั้นตอน 2.1: แทนที่ด้วยสตริงที่กำหนด
ขั้นตอน 3: คืนค่าสตริงที่แก้ไขแล้ว
ตัวอย่างโค้ด
#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.