AlgoMaster Logo

Toggle Case of Every Character

Last Updated: June 7, 2026

easy
2 min read

Understanding the Problem

Every letter in the new string has its case flipped, while everything that is not a letter stays untouched. A digit like 5, a space, or a punctuation mark passes through unchanged.

Strings are immutable in many languages, so you cannot edit the original characters in place. You build the result one character at a time, deciding for each whether it is uppercase, lowercase, or something else, then appending the correct version.

The case flip should avoid a long table of conversions. Listing every pair, A to a, B to b, and so on, is 52 cases and easy to get wrong. The numeric encoding of characters handles every letter with one rule instead.

Key Constraints:

  • 0 <= s.length <= 1000 → The string can be empty, in which case the result is empty too. The code must run cleanly when there is nothing to flip.
  • Only letters change → Digits, spaces, and symbols pass through unchanged.

Approach 1: ASCII Arithmetic

Intuition

Every character maps to a number through the ASCII encoding. A is 65 and a is 97, a gap of exactly 32, and that same gap holds for every letter: B is 66 and b is 98, Z is 90 and z is 122.

This regular spacing is what you exploit. Add 32 to make an uppercase letter lowercase, subtract 32 to make a lowercase letter uppercase. No lookup table is needed: check whether the character is upper or lower, then adjust by 32 in the right direction. Any non-letter is copied straight into the result.

Algorithm

  1. Create an empty buffer to build the result string.
  2. Walk through the input string one character at a time.
  3. If the character is an uppercase letter from A to Z, add 32 to its code to get the lowercase version.
  4. If the character is a lowercase letter from a to z, subtract 32 to get the uppercase version.
  5. If the character is anything else, keep it unchanged.
  6. Append the resulting character to the buffer and continue until the string ends.

Example Walkthrough

1Index 0 is 'H', uppercase. Add 32 to get 'h'. result = "h".
0
i
H
1
i
2
3
9
4
!
1/5

Take the string "Hi 9!". At index 0 the character is H, uppercase, so adding 32 turns it into h, giving "h". At index 1 the character is i, lowercase, so subtracting 32 turns it into I, giving "hI". At index 2 the space is not a letter, so it is copied unchanged, giving "hI ". At index 3 the digit 9 is copied unchanged, giving "hI 9". At index 4 the punctuation mark ! is copied unchanged, giving "hI 9!". Only the two letters changed.

0
h
1
I
2
3
9
4
!
result

Code