Step 5 of 6
Characters are numbers
A char is a small integer holding a character code, so you can do arithmetic and comparisons on characters. In ASCII, the letters 'a' to 'z' have consecutive codes (97 to 122), and so do 'A' to 'Z' (65 to 90) and the digits '0' to '9' (48 to 57). That makes several tricks possible:
c >= 'a' && c <= 'z'checks for a lowercase letter.c - 'a'gives a letter's position in the alphabet ('c' - 'a'is 2).c - '0'turns a digit character into its number ('7' - '0'is 7).- The gap between lowercase and uppercase is the same for every letter:
'a' - 'A'is 32.
#include <stdio.h>
int digit_sum(const char s[]) {
int sum = 0;
for (int i = 0; s[i] != '\0'; i++) {
if (s[i] >= '0' && s[i] <= '9') {
sum += s[i] - '0';
}
}
return sum;
}
int main(void) {
printf("%d\n", digit_sum("a1b2c3"));
printf("%c%c\n", 'a' + 7, 'A' + ('e' - 'a'));
return 0;
}
6
hE
The <ctype.h> helpers
The standard library has ready-made, readable versions of these checks: isdigit(c), isalpha(c), islower(c), isupper(c), isspace(c), and converters toupper(c) and tolower(c), which return the converted character (or the same character if there's nothing to convert). They're clearer than hand-written ranges, so prefer them in real code.
Changing a string in place
To modify a string, loop over it and assign to s[i]. Only change the characters that need changing; everything else, including spaces, digits and the terminator, must stay as it was.
Your task
Write void to_upper(char s[]) that converts every lowercase letter in the string to uppercase in place. Leave other characters alone.
Challenge 2
Write void capitalize(char s[]) that makes the first letter of every word uppercase and every other letter lowercase, in place. A word starts at the beginning or right after a space.
Challenge 3
Write void caesar(char s[], int shift) that shifts every letter shift places forward in the alphabet (with shift from 0 to 25), wrapping around from z to a. Keep capitals capital, and leave everything that isn't a letter alone. caesar("Hello, World!", 13) gives "Uryyb, Jbeyq!".
Previous: Compare strings correctly Next: Challenge: palindromes