VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-alternate-characters-string-upper-case/

⇱ Toggle the Case of Each Character in a String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Toggle the Case of Each Character in a String

Last Updated : 31 Mar, 2026

Given a string s consisting of English letters (both uppercase and lowercase), convert each character to its opposite case that is, change every lowercase letter to uppercase, and every uppercase letter to lowercase.

Examples:

Input : s = "geeksForgEeks"
Output : "GEEKSfORGeEKS"
Explanation : All lower case characters are changed into upper case and vice versa.

Input : s = "SMALLcase"
Output : "smallCASE"
Explanation : All lower case characters are changed into upper case and vice versa.

Library-Based Case Toggling - O(n) Time and O(n) Space

The idea involves initializing an empty string. Iterate a for loop over the given string and check each character whether is lowercase or uppercase using isupper() and islower(). If lowercase converts the character to uppercase using upper() and append to empty string, similarly with uppercase.


Output
gEeKsFoRgEeKs

Using ASCII values - O(n) Time and O(1) Space

Iterate through each character of the string and toggle its case using ASCII values: subtract 32 to convert lowercase to uppercase, and add 32 to convert uppercase to lowercase.


Output
gEeKsFoRgEeKs

Toggle Case Using XOR on 5th Bit - O(n) Time and O(1) Space

The core logic behind letter case toggling is based on the ASCII representation of characters. In ASCII, the difference between any lowercase and its corresponding uppercase letter is always 32 - for example, 'a' - 'A' = 32, 'b' - 'B' = 32, and so on. This means that toggling the 5th bit (i.e., 1 << 5 = 32) of an alphabetic character using XOR (ch ^= 1 << 5) effectively switches its case - converting lowercase to uppercase and vice versa in constant time.


Output
gEeKsFoRgEeKs
Comment
Article Tags: