Write a C++ Program to Find the Number of Vowels, Consonants, Digits and White Spaces in a String

In this post, we will explore how to write a C++ program to find the number of vowels, consonants, digits, and white spaces in a string.

This can be a useful exercise for beginners to practice string manipulation and iteration in C++.

To get started, we will define a function that takes a string as input and returns the count of vowels, consonants, digits, and white spaces. Here’s the code for the function:

#include <iostream>
using namespace std;

int countCharacters(string str) {
    int vowels = 0, consonants = 0, digits = 0, spaces = 0;
    for (int i = 0; i < str.length(); i++) {
        char c = str[i];
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
            c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
            vowels++;
        } else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
            consonants++;
        } else if (c >= '0' && c <= '9') {
            digits++;
        } else if (c == ' ') {
            spaces++;
        }
    }
    return vowels, consonants, digits, spaces;
}

This function takes a string input str and initializes variables for counting vowels, consonants, digits, and spaces to 0.

The for loop iterates over each character in the string, and checks whether it is a vowel, consonant, digit, or space.

The if-else statement inside the loop increments the corresponding count variable based on the character type.

Finally, the function returns the count of each character type using the comma operator.

To use this function, we can call it from main() and provide a string input to count the number of vowels, consonants, digits, and spaces. Here’s an example code snippet:

int main() {
    string str = "Hello World! 123";
    int vowels, consonants, digits, spaces;
    tie(vowels, consonants, digits, spaces) = countCharacters(str);
    cout << "Number of vowels: " << vowels << endl;
    cout << "Number of consonants: " << consonants << endl;
    cout << "Number of digits: " << digits << endl;
    cout << "Number of spaces: " << spaces << endl;
    return 0;
}

In this code snippet, we provide the string “Hello World! 123” as input to the countCharacters() function.

The tie() function is used to unpack the return values into separate variables, which are then printed to the console using cout.

This is a simple example of how to count the number of vowels, consonants, digits, and spaces in a string using C++.