Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีลบตัวอักษรบางตัวออกจาก string ใน C++


ในส่วนนี้ เราจะดูวิธีลบตัวอักษรบางตัวออกจาก string ใน C++ ใน C++ เราสามารถทำได้ง่ายมากโดยใช้ erase() และ remove() function ฟังก์ชัน remove รับ starting และ ending address ของ string และ character ที่จะถูกลบ

Input: A number string "ABAABACCABA"
Output: "BBCCB"

Algorithm

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