The toolbox <ctype.h> has handy functions for single characters:
| Function | Answers / does |
|---|---|
isalpha(c) | Is it a letter? |
isdigit(c) | Is it a digit 0–9? |
isspace(c) | Is it a space, tab or new line? |
isupper(c) / islower(c) | Is it a capital / small letter? |
toupper(c) / tolower(c) | Give back the capital / small version |
The is... functions return a non-zero number for true and 0 for false, so you use them in if:
#include <stdio.h>
#include <ctype.h>
int main() {
char text[40] = "Room 42, Floor 3!";
int letters = 0;
int digits = 0;
for (int i = 0; text[i] != '\0'; i++) {
if (isalpha(text[i])) {
letters++;
} else if (isdigit(text[i])) {
digits++;
}
}
printf("Letters: %d, Digits: %d\n", letters, digits);
return 0;
}Output
Letters: 9, Digits: 3
Shouting: make everything capital
#include <stdio.h>
#include <ctype.h>
int main() {
char msg[30] = "please hurry";
for (int i = 0; msg[i] != '\0'; i++) {
msg[i] = toupper(msg[i]);
}
printf("%s\n", msg);
return 0;
}Output
PLEASE HURRY
Characters are numbers
Remember that a char is stored as a number. The letters 'a' to 'z' come one after another, and so do '0' to '9'. That lets you do maths with them:
#include <stdio.h>
int main() {
char digit = '7';
int value = digit - '0'; // turns the character '7' into the number 7
printf("%d\n", value * 2);
char letter = 'c';
printf("%c\n", letter + 1); // the next letter
return 0;
}Output
14 d
Tip:
c - '0'is the classic trick to turn a digit character into its number.