The task of counting characters, such as vowels and consonants, in a string is a common operation in text processing, which is often tackled in programming exercises and projects. This is particularly useful in areas like linguistic analysis, text normalization, and preparing data for further processing in Natural Language Processing (NLP).
In this article, you will learn how to develop a C program that accurately counts the number of vowels, consonants, digits, and special characters in a given string. Through detailed code examples and explanations, grasp how to implement and utilize basic programming concepts in C, such as loops and condition checking.
Declare a character array to hold the input string.
Use printf
and scanf
to get the input string from the user.
char str[100];
printf("Enter a string: ");
scanf("%99[^\n]", str); // Reads a line of text
This code snippet initializes a character array str
of size 100 and reads a line from the user, storing it in str
.
Initialize counters for vowels, consonants, digits, and special characters.
Use a loop to iterate over each character in the string and classify it.
int vowels = 0, consonants = 0, digits = 0, specialChars = 0;
int i = 0;
char ch;
while (str[i] != '\0') {
ch = str[i];
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
// Check for vowels (both uppercase and lowercase)
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
vowels++;
else
consonants++;
} else if (ch >= '0' && ch <= '9') {
digits++;
} else {
specialChars++;
}
i++;
}
This block counts each type of character. It uses ASCII values to differentiate between alphabetic characters, digits, and special characters. Vowels and consonants are checked by specific conditions.
Print the results using printf
.
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
printf("Digits: %d\n", digits);
printf("Special characters: %d\n", specialChars);
Here, the counts of vowels, consonants, digits, and special characters are displayed on the console.
Successfully applying basic C programming techniques, you can design a program that categorizes and counts different types of characters in a string. The example provided here captures vowels, consonants, numeric digits, and special characters inclusively. The ability to distinguish between these character types lays a foundation for more complex text analysis and processing tasks. Use this program as a stepping stone for more intricate projects, such as automated readability assessments or text-based data mining.