Count Number Of Vowels Consonants And Digits In A String In C
ADVERTISEMENTS
Here's how to count vowels, consonants, and digits in a string using the C programming language. This article will guide you through the necessary steps and provide a practical example.
Introduction
Strings are fundamental data types, and character classification within them is a common task. In this article, you will learn how to efficiently count the occurrences of vowels, consonants, and digits within any given string in C.Problem Statement
When processing textual data, it's often necessary to categorize characters. The problem at hand is to take an input string and determine the total count of English vowels (a, e, i, o, u, case-insensitive), consonants, and numerical digits (0-9) present in it, ignoring any other special characters or spaces.Example
Consider the string:"Hello World 123!"
The desired output would be:- Vowels: 3 (e, o, o)
- Consonants: 7 (H, l, l, W, r, l, d)
- Digits: 3 (1, 2, 3)
Background & Knowledge Prerequisites
To understand this tutorial, you should have a basic understanding of:- C Language Basics: Variables, data types, and fundamental operators.
- Strings in C: How strings are represented as character arrays and terminated by the null character (
\0). - Loops: Specifically, the
fororwhileloop for iterating through characters in a string. - Conditional Statements:
if,else if, andelsefor character comparison and classification. - ASCII Values: Understanding that characters have corresponding integer values, which helps in range checking.
- Character Functions: Basic use of
functions likeisalpha(),isdigit(),tolower(), though we will implement without them for educational purposes to show manual checks.
Use Cases or Case Studies
Counting character types in a string has several practical applications:- Data Validation: Ensuring that user input meets specific criteria, like passwords requiring a certain number of digits or letters.
- Text Analysis: In natural language processing, this can be a preliminary step to analyze the composition of text, such as determining letter frequency or identifying numerical data.
- Simple Cryptography: Basic character manipulation and analysis can be part of simple encoding or decoding schemes.
- Educational Tools: Developing programs to help students learn about string manipulation and character properties.
- Form Processing: Extracting specific information from forms, like separating numerical IDs from textual descriptions.
Solution Approaches
We will implement a straightforward iterative approach that scans the string character by character and classifies each one using conditional logic.
Approach 1: Iterative Classification with if-else if
This approach involves iterating through each character of the string and using a series of if-else if statements to check if the character is a digit, then a vowel (case-insensitive), or finally a consonant.
- Summary: Loop through the string, converting each alphabetic character to lowercase for consistent vowel/consonant checking, and increment respective counters.
// Count Vowels Consonants Digits
#include <stdio.h>
#include <string.h> // For strlen()
#include <ctype.h> // For tolower() and isalpha(), isdigit()
int main() {
char str[100];
int vowels = 0;
int consonants = 0;
int digits = 0;
int i;
// Step 1: Get input string from the user
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Reads string including spaces
// Remove the newline character if present from fgets
str[strcspn(str, "\\n")] = 0;
// Step 2: Iterate through each character of the string
for (i = 0; str[i] != '\\0'; i++) {
char ch = str[i];
// Step 3: Check if the character is a digit
if (ch >= '0' && ch <= '9') {
digits++;
}
// Step 4: Check if the character is an alphabet
else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
// Convert to lowercase for consistent vowel checking
ch = tolower(ch);
// Step 5: Check if the lowercase alphabet is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
}
// Step 6: Otherwise, it's a consonant
else {
consonants++;
}
}
// Characters that are not digits or alphabets (e.g., spaces, punctuation) are ignored.
}
// Step 7: Print the final counts
printf("Number of Vowels: %d\\n", vowels);
printf("Number of Consonants: %d\\n", consonants);
printf("Number of Digits: %d\\n", digits);
return 0;
}
- Sample Output:
Enter a string: Programming in C is Fun! 123
Number of Vowels: 7
Number of Consonants: 15
Number of Digits: 3
- Stepwise Explanation:
- Initialization: Three integer variables (
vowels,consonants,digits) are initialized to zero to store the counts. A character arraystris declared to hold the input string. - Input: The program prompts the user to enter a string.
fgets()is used to read the input, which is safer thanscanf()as it prevents buffer overflows and reads entire lines including spaces.strcspn()is used to remove the trailing newline character thatfgets()often includes. - Iteration: A
forloop iterates through each character of the string until the null terminator (\0) is encountered. - Digit Check: Inside the loop, the current character
chis first checked to see if it's a digit ('0'to'9'). If it is, thedigitscounter is incremented. - Alphabet Check: If the character is not a digit, the program proceeds to check if it's an alphabet (either lowercase
'a'to'z'or uppercase'A'to'Z'). - Lowercase Conversion: If it's an alphabet,
tolower(ch)is used to convert the character to its lowercase equivalent. This simplifies the vowel check, as only lowercase vowels need to be explicitly listed. - Vowel Check: The lowercase alphabet character is then compared against the five vowels (
'a','e','i','o','u'). If it matches any, thevowelscounter is incremented. - Consonant Check: If the character is an alphabet but not a vowel, it must be a consonant. In this case, the
consonantscounter is incremented. - Output: After the loop finishes processing all characters, the final counts for vowels, consonants, and digits are printed to the console.
Conclusion
Counting specific character types in a string is a fundamental string manipulation task in C. By iterating through the string and applying simple conditional logic, we can accurately categorize each character as a vowel, consonant, or digit. This method provides a clear and efficient way to analyze string content.Summary- Initialize counters for vowels, consonants, and digits to zero.
- Read the input string, preferably using
fgets() to handle spaces and prevent buffer overflows. - Loop through each character of the string until the null terminator (
\0). - Inside the loop:
- Check if the character is a digit using its ASCII range (
'0' to '9'). - If not a digit, check if it's an alphabet (both uppercase and lowercase ranges).
- Convert alphabetic characters to lowercase using
tolower() for simplified checking. - Check if the lowercase alphabet is a vowel.
- If it's an alphabet but not a vowel, categorize it as a consonant.
- Print the final counts.
fgets() to handle spaces and prevent buffer overflows.\0).'0' to '9').tolower() for simplified checking.