Question 5
Back to Exercise
Classify each character as a vowel, consonant, digit, space or special character.
Solution
#include <ctype.h>
#include <stdio.h>
const char *kind(char ch) {
unsigned char c = (unsigned char) ch;
if (isdigit(c))
return "digit";
if (!isalpha(c))
return isspace(c) ? "space" : "special";
switch (tolower(c)) {
case 'a': case 'e': case 'i': case 'o': case 'u':
return "vowel";
default:
return "consonant";
}
}
int main(void) {
const char *s = "aZ7 #E";
for (const char *p = s; *p; p++)
printf("'%c' %s\n", *p, kind(*p));
return 0;
}
'a' vowel 'Z' consonant '7' digit ' ' space '#' special 'E' vowel
The ctype checks rule out digits and non-letters first, so the switch only sees letters. tolower() means five case labels cover both cases.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!