Last Updated: June 7, 2026
Change the case of the letters in a string and leave everything else alone. The toUpper flag sets the direction. When true, every lowercase letter becomes uppercase. When false, every uppercase letter becomes lowercase. Digits, spaces, and punctuation are copied unchanged, and a letter already in the target case stays as it is.
The conversion rests on how letters are stored in ASCII. The uppercase letters A through Z occupy codes 65 through 90, and the lowercase letters a through z occupy codes 97 through 122. Each lowercase letter sits exactly 32 codes above its uppercase twin, since 97 - 65 is 32. Subtracting 32 from a lowercase letter yields its uppercase form, and adding 32 to an uppercase letter yields its lowercase form.
The shift applies only to letters in the wrong case. Checking the range before shifting leaves non-letters and already-correct letters untouched.
0 <= s.length <= 1000 → The string can be empty, in which case the result is also empty. The code must handle that without indexing into anything.Each character is independent of the rest, so walk through them one at a time. When toUpper is true, subtract 32 from any character in the a to z range and leave the rest. When toUpper is false, add 32 to any character in the A to Z range and leave the rest.
Collect the converted characters into a result string. Each character costs one comparison and at most one addition or subtraction, so the pass is linear in the length of the string.
c in s.toUpper is true and c is between a and z, subtract 32 from its code.toUpper is false and c is between A and Z, add 32 to its code.c unchanged. Append the resulting character to the buffer.Take the string "Mix 1" with toUpper set to true. At index 0 the character is M, which is already uppercase, so it is kept and the result is "M". At index 1 the character is i, a lowercase letter, so subtracting 32 turns it into I, giving "MI". At index 2 the character is x, also lowercase, so it becomes X, giving "MIX". At index 3 the character is a space, which is not a letter, so it is copied unchanged, giving "MIX ". At index 4 the character is 1, a digit, so it too is copied unchanged, giving "MIX 1". The pass is complete.