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

ลบสระออกจากสตริงใน C++ (Remove Vowels)

ลบสระ (a, e, i, o, u ทั้งพิมพ์เล็กและใหญ่) ออกจากสตริง

อัลกอริทึม

  1. รับสตริง Input
  2. ตรวจสอบแต่ละตัวอักษร หากไม่ใช่สระ คัดลอกไปสตริงใหม่
  3. คืนค่าสตริงใหม่

ตัวอย่างโค้ด (ปรับปรุงจากต้นฉบับ)

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

bool isVowel(char ch) {
    ch = tolower(ch);
    return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}

string removeVowels(const string& str) {
    string result;
    result.reserve(str.length());
    for (char ch : str) {
        if (!isVowel(ch))
            result += ch;
    }
    return result;
}

int main() {
    string input;
    cout << "Enter a string: ";
    getline(cin, input);

    string output = removeVowels(input);
    cout << "String after removing vowels: " << output << endl;

    return 0;
}

ตัวอย่างการทำงาน

Enter a string: ajaykumar
String after removing vowels: jykmr

วิธีอื่น: Erase-Remove Idiom

string removeVowelsErase(string str) {
    str.erase(remove_if(str.begin(), str.end(), 
        [](char c){ return isVowel(c); }), str.end());
    return str;
}

C++20: ranges::remove_if

#include 
#include 
string removeVowelsModern(string str) {
    auto is_vowel = [](char c) { 
        c = tolower(c); 
        return c=='a'||c=='e'||c=='i'||c=='o'||c=='u'; 
    };
    str.erase(ranges::remove_if(str, is_vowel).begin(), str.end());
    return str;
}