เพื่อหาสระจากสตริง เราต้องวนลูปผ่านตัวอักษรแต่ละตัวของสตริง ที่นี่เราต้องใช้ pointers เพื่อเคลื่อนที่ผ่านสตริง สำหรับนี้เราต้องใช้ C-style strings ถ้าสตริงถูกชี้โดย str แล้ว *str จะเก็บตัวอักษรแรกในตอนต้น แล้วถ้าเพิ่ม str *str จะชี้ตัวอักษรถัดไป และต่อไป หากตัวอักษรอยู่ใน [a,e,i,o,u] หรือ [A,E,I,O,U] แล้วเป็นสระ เราจะเพิ่มตัวนับ
อัลกอริทึม
countVowels(str)
begin
count := 0
for each character ch in str, do
if ch is in [a,e,i,o,u] or [A, E, I, O, U], then
count := count + 1
end if
done
return count
end
ตัวอย่าง
#include<iostream>
using namespace std;
int countVowels(const char *myStr) {
int count = 0;
while((*myStr) != '\0') {
if(*myStr == 'a' || *myStr == 'e' || *myStr == 'i' || *myStr == 'o' || *myStr == 'u' || *myStr == 'A' || *myStr == 'E' || *myStr == 'I' || *myStr == 'O' || *myStr == 'U') {
count++;
}
myStr++;
}
return count;
}
int main() {
string myStr;
cout << "Enter String: ";
cin >> myStr;
cout << "Number of Vowels: " << countVowels(myStr.c_str());
}
ผลลัพธ์
Enter String: EDucation Number of Vowels: 5