C++ How To Count Vowels in a String
Count Vowels in a String
Loop through the characters of a string, and count the vowels (a, e, i, o and u):
Example
string text = "Hello World";
int count = 0;
for (char c : text) {
c = tolower(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
count++;
}
}
cout << "Number of vowels: " << count;
Explanation:
The loop goes through each character c in the string.tolower() makes the character lowercase, so "A" and "a" are both counted.
"Hello World" has 3 vowels: e, o and o.