Character Functions
The library ctype.h has functions that work with one character. Two of them change it:
toupper(c)gives the uppercase letter:toupper('a')is'A';tolower(c)gives the lowercase letter:tolower('Q')is'q'.
Other characters stay as they are: toupper('5') is '5', and toupper('A') is 'A'.
#include <ctype.h>
#include <stdio.h>
int main(void) {
char name[] = "eva";
name[0] = toupper(name[0]);
printf("%s\n", name);
return 0;
}This prints:
Evatoupper doesn't change the character you give it. It gives you a new character, and you have to store it: name[0] = toupper(name[0]);. A line with only toupper(name[0]); compiles, but the name stays eva, because the new character is thrown away. (The result is a number of type int, the code of the character. When you store it in a char or print it with %c, it's a character again.)
Other functions answer a question about a character:
isupper(c): is it an uppercase letter?isalpha(c): is it a letter?isdigit(c): is it a digit, from'0'to'9'?
The answer is a number: 0 means no, and any other number means yes. So use them directly as a condition, as you know from the lesson on conditions: if (isdigit(c)). This loop counts the digits in a code:
char code[] = "R2D2";
int digits = 0;
for (int i = 0; code[i] != '\0'; i++) {
if (isdigit(code[i])) {
digits++;
}
}
printf("Digits: %d\n", digits);This prints:
Digits: 2These functions only know the letters of the English alphabet, without accents. One more reason to keep the strings you go through character by character without accents.
Instructions
Someone typed the city with Caps Lock on. Add #include <ctype.h> and fix city: change its first character to uppercase with toupper, and all the others to lowercase with tolower, in a loop that starts at the index 1. Then print it: Fixed: Prague.
Below that, create char code[] = "B4X-27Q9";. Go through it in a loop, count its digits with isdigit and its letters with isalpha, and print Digits: 4, letters: 3.
Start programming for free
8/10