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

สตริงสลับระหว่างสระและพยัญชนะใน C/C++


มีสตริงให้ จัดเรียงตัวอักษรในสตริงให้สระและพยัญชนะสลับกัน ถ้าจัดเรียงไม่ได้พิมพ์ "not possible"

ลำดับของสระเทียบกันและพยัญชนะเทียบกันควรคงไว้

Input: abce Output: abec

คำอธิบาย

  • หาจำนวนสระและพยัญชนะในสตริง
  • ถ้าความต่างระหว่างจำนวนสระและพยัญชนะมากกว่า 1 คืนค่า "Not Possible"
  • ถ้ามีสระมากกว่าพยัญชนะ พิมพ์สระแรกก่อนและเรียกซ้ำสำหรับสตริงที่เหลือ
  • ถ้ามีพยัญชนะมากกว่าสระ พิมพ์พยัญชนะแรกก่อนและเรียกซ้ำสำหรับสตริงที่เหลือ
  • ถ้าจำนวนสระและพยัญชนะเท่ากัน เปรียบเทียบสระแรกกับพยัญชนะแรก และพิมพ์ตัวที่น้อยกว่าก่อน

ตัวอย่างโค้ด C++

#include 
using namespace std;
bool isVowel(char ch) {
    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u')
        return true;
    return false;
}
string createAltStr(string str1, string str2, int start, int l) {
    string finalStr = "";
    for (int i=0, j=start; j= 2)
        return "no such string";
    if (nv > nc)
        return (vstr.at(0) + createAltStr(cstr, vstr, 1, nv));
    if (nc > nv)
        return (cstr.at(0) + createAltStr(vstr, cstr, 1, nc));
    if (cstr.at(0) < vstr.at(0))
        return createAltStr(cstr, vstr, 0, nv);
    return createAltStr(vstr, cstr, 0, nc);
}
int main() {
    string str = "abde";
    cout << findAltStr(str);
    return 0;
}