Code Logo

Toggle Case

Published at25 Jul 2026
Easy 1 views
Like0

Given a string, toggle the case of each letter: uppercase letters become lowercase and lowercase letters become uppercase. Non-alphabetic characters remain unchanged. Return the transformed string.

For example, "Hello World" becomes "hELLO wORLD". "ABC123" becomes "abc123". An empty string returns "".

Case toggling is a text transformation operation used in formatting, cryptography (ROT13 variant), and accessibility. It tests character-by-character manipulation and ASCII value arithmetic.

The solution iterates through each character. If it is uppercase (between 'A' and 'Z'), convert to lowercase by adding 32 to its ASCII value. If it is lowercase (between 'a' and 'z'), convert to uppercase by subtracting 32. Otherwise, leave it unchanged.

Edge cases include an empty string (return ""), a string with no letters (return unchanged), and Unicode characters (only standard ASCII letters are toggled).

Example Input & Output

Example 1
Input
"ABC"
Output
"abc"
Explanation

Uppercase to lowercase

Example 2
Input
""
Output
""
Explanation

Empty string

Example 3
Input
"Hello World"
Output
"hELLO wORLD"
Explanation

Toggle case of each letter

Example 4
Input
"123!@#"
Output
"123!@#"
Explanation

Non-letters unchanged

Example 5
Input
"abc"
Output
"ABC"
Explanation

Lowercase to uppercase

Algorithm Flow

Recommendation Algorithm Flow for Toggle Case

Solution Approach

Iterate through the string and toggle each letter's case using ASCII value arithmetic.

function toggleCase(s)
  result = ""
  for i = 0 to length(s) - 1
    c = s[i]
    if c >= 'A' and c <= 'Z' then result = result + lowercase(c)
    else if c >= 'a' and c <= 'z' then result = result + uppercase(c)
    else result = result + c
  return result

Build a result string character by character. For uppercase letters, convert to lowercase. For lowercase letters, convert to uppercase. For all other characters, append unchanged.

Time complexity is O(n), space complexity is O(n) for the result.

Best Answers

java
class Solution {
    public String solution(String s) {
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<s.length();i++){char c=s.charAt(i);
            if(Character.isUpperCase(c))sb.append(Character.toLowerCase(c));
            else if(Character.isLowerCase(c))sb.append(Character.toUpperCase(c));
            else sb.append(c);
        }return sb.toString();
    }
}