Count the vowels in a string

Description: Count the vowels and the consonants in "Learn C++ Programming".

Hint:

  • Use std::isalpha and look for the letter in "aeiou".

Solution

#include <cctype>
#include <iostream>
#include <string>

int main() {
    std::string text = "Learn C++ Programming";
    int vowels = 0, consonants = 0;
    for (unsigned char c : text) {
        if (!std::isalpha(c)) continue;
        if (std::string("aeiou").find(static_cast<char>(std::tolower(c))) != std::string::npos) vowels++;
        else consonants++;
    }
    std::cout << "Vowels: " << vowels << ", consonants: " << consonants << '\n';
}
Output

Vowels: 5, consonants: 12

How it works

  • Spaces, + signs and other characters are skipped with continue.

Read C++ Strings.


Learn more about the similar topics:
Tutorials
C++ Strings: std::string and string_view
C++ Arrays and std::array
C++ Vectors (std::vector)
Exercises & Assignments
Reverse a string
Check if a string is a palindrome
Count the vowels in a string
Find the second largest number in a vector
Sort a vector with bubble sort
Transpose a matrix
Interview Questions & Answers
What is the difference between an array and a vector in C++?
What is the difference between std::string and a char array in C++?