Skip to main content

ulstr — Toggle Letter Case

Allowed functions: write

Write a program that takes a string and reverses the case of all its letters. Other characters remain unchanged.

You must display the result followed by a newline. If the number of arguments is not 1, the program displays a newline.

Examples

$>./ulstr "L'eSPrit nE peUt plUs pRogResSer s'Il staGne et sI peRsIsTent VAnIte et auto-justification." | cat -e
l'EspRIT Ne PEuT PLuS PrOGrESsER S'iL STAgNE ET Si PErSiStENT vaNiTE ET AUTO-JUSTIFICATION.$
$>./ulstr "3:21 Ba tOut moUn ki Ka di KE m'en Ka fe fot" | cat -e
3:21 bA ToUT MOuN KI kA DI ke M'EN kA FE FOT$
$>./ulstr | cat -e
$

Solution

Download ultstr.c
#include <unistd.h>

int main(int l, char **v) {

if (l != 2) {

write(1, "\n", 1);
return 0;
}

char *str = v[1];
char c;
while (*str) {
c = *str;
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
c = *str + 32 - 64 * (*str >= 'a');
write(1, &c, 1);
str++;
}

write(1, "\n", 1);
}

How It Works

Goal: Toggle the case of every letter in a string — uppercase becomes lowercase and vice versa.

Approach: Use ASCII arithmetic to flip the case by adding 32 (to go from upper to lower) or subtracting 32 (lower to upper), combined into one expression.

Step by step:

  1. If argument count is not 2, print a newline and exit.
  2. For each character, check if it is a letter.
  3. If it is a letter, compute the toggled character: add 32 to the ASCII value, but subtract 64 if the character is already lowercase (*str >= 'a'). This effectively adds 32 for uppercase letters and subtracts 32 for lowercase letters.
  4. Write the resulting character to stdout.

Key concept: The ASCII case difference is 32 — lowercase and uppercase letters are exactly 32 apart in ASCII, so toggling case is just adding or subtracting 32.