Mô tả bài toán
Cho chuỗi và số X. In ra X nguyên âm đầu tiên (a,e,i,o,u), không phân biệt chữ hoa/thường. Nếu thiếu → in -1.
Ví dụ
str="learn C programming language", X=5 → Output: eaoai.
Giải thuật
Duyệt chuỗi, kiểm tra ký tự có phải nguyên âm (tolower). Gom vào chuỗi kết quả cho đến độ dài X.
Mã nguồn C++
#include <iostream>
#include <string>
using namespace std;
bool isVowel(char c) {
c = tolower(c);
return c=='a'||c=='e'||c=='i'||c=='o'||c=='u';
}
string findXVowelsString(string s, int x) {
string res;
for (char c : s) if (isVowel(c)) {
res += c;
if (res.size() == x) return res;
}
return "-1";
}
int main() {
string str = "learn C programming language";
int x = 5;
cout << "First " << x << " vowels: " << findXVowelsString(str,x);
return 0;
}
Đầu ra
The first 5 vowels from the string are eaoai