ในส่วนนี้ เราจะมาดูวิธีการลบอักขระบางตัวออกจากสตริงใน C++ ใน C ++ เราสามารถทำงานนี้ได้อย่างง่ายดายโดยใช้ฟังก์ชัน Erase() และ Remove() ฟังก์ชันลบใช้ที่อยู่เริ่มต้นและสิ้นสุดของสตริง และอักขระที่จะถูกลบออก
Input: A number string “ABAABACCABA” Output: “BBCCB”
อัลกอริทึม
Step 1:Take a string Step 2: Remove each occurrence of a specific character using remove() function Step 3: Print the result. Step 4: End
โค้ดตัวอย่าง
#include<iostream>
#include<algorithm>
using namespace std;
main() {
string my_str = "ABAABACCABA";
cout << "Initial string: " << my_str << endl;
my_str.erase(remove(my_str.begin(), my_str.end(), 'A'), my_str.end()); //remove A from string
cout << "Final string: " << my_str;
} ผลลัพธ์
Initial string: ABAABACCABA Final string: BBCCB