![]() |
VOOZH | about |
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.
Table of Content
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.
gEeKsFoRgEeKs
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.
gEeKsFoRgEeKs
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.
gEeKsFoRgEeKs