Strings · beginner
C Program to Count Vowels and Consonants in a String
Count the vowels, consonants, digits and spaces in a string in C by looping until the null terminator and classifying each character with ctype.h.
- loop until '\0'
- strchr()
- isalpha(), isdigit(), isspace()
- tolower()
Counting character types is a good exercise in walking a C string: loop until the terminating '\0' and classify each character. ctype.h has the tests for letters, digits and whitespace; strchr() checks whether a character is one of a set.
The program
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void) {
const char *text = "Programming in C, since 1972!";
int vowels = 0, consonants = 0, digits = 0, spaces = 0;
for (const char *p = text; *p != '\0'; p++) {
unsigned char ch = (unsigned char)*p;
if (isalpha(ch)) {
if (strchr("aeiou", tolower(ch)))
vowels++;
else
consonants++;
} else if (isdigit(ch)) {
digits++;
} else if (isspace(ch)) {
spaces++;
}
}
printf("Vowels: %d, consonants: %d, digits: %d, spaces: %d\n", vowels, consonants, digits, spaces);
return 0;
}Vowels: 6, consonants: 13, digits: 4, spaces: 4How it works
- The pointer p walks through the string; *p is the current character and the loop stops at '\0'.
- isalpha() is true for letters. strchr("aeiou", tolower(ch)) returns a non-null pointer when the lowercase letter is a vowel.
- Other letters are consonants; isdigit() and isspace() count digits and whitespace.
- Punctuation such as the comma and "!" is not counted in any group.
Another way: Count each vowel separately
An int array indexed by letter (ch - 'a') counts every letter at once; the vowels are then read from it.
#include <ctype.h>
#include <stdio.h>
int main(void) {
const char *text = "Programming in C";
int counts[26] = {0};
for (int i = 0; text[i]; i++) {
unsigned char ch = (unsigned char)text[i];
if (isalpha(ch))
counts[tolower(ch) - 'a']++;
}
const char *vowels = "aeiou";
for (int i = 0; vowels[i]; i++)
printf("%c: %d\n", vowels[i], counts[vowels[i] - 'a']);
return 0;
}a: 1
e: 0
i: 2
o: 1
u: 0Common mistakes
- Checking only lowercase vowels, so "A" and "E" are counted as consonants.
- Counting every non-vowel as a consonant, including spaces, digits and punctuation.
- strchr("aeiou", ch) also matches ch == '\0' (it finds the terminator); here that cannot happen because only letters reach it.
Try it yourself
- Read a line with fgets() and count its vowels.
- Print the most frequent letter in the text.
Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 C examples, or write your own program in the online C Compiler.