Classifying characters in C
ctype.h answers what a character is, without hard-coding ASCII ranges.
int count_digits(const char *text) {
int digits = 0;
for (const char *p = text; *p != '\0'; p++) {
unsigned char c = (unsigned char) *p;
if (isdigit(c)) {
digits++;
}
}
return digits;
}
void shout(char *text) {
for (char *p = text; *p; p++) {
*p = (char) toupper((unsigned char) *p);
}
}
How it works
isalpha,isdigitandisspaceclassify one character.toupperandtolowerconvert it.- Pass the character as an
unsigned charto stay defined.
Keywords and builtins used here
charconstcount_digitsforifintreturnshoutunsignedvoid
The run, in numbers
- Lines
- 16
- Characters to type
- 288
- Tokens
- 107
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 71 seconds.
Step 5 of 5 in Arrays & strings, step 26 of 35 in Language basics.