Open In App

Toggle the Case of Each Character in a String

Last Updated : 14 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = "capiTAlize"
Output : "CAPItaLIZE"
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.

[Naive Approach] Using index() method - O(n) Time and O(n) space

The primary idea involves use of two fixed lookup strings, one for uppercase and one for lowercase, and for each character finds its index in one string to pick the corresponding opposite‑case character from the other, building a new toggled string.

C++
#include <iostream>
using namespace std;

string toggleChar(string& str) {
    string result = "";
    string uppalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string lowalpha = "abcdefghijklmnopqrstuvwxyz";
    
    // Iterate over each character in the input string
    for (char ch : str) {
        
        // If character is uppercase, find its position
        // and get the corresponding lowercase
        if (uppalpha.find(ch) != string::npos) {
            result += lowalpha[uppalpha.find(ch)];
        } else {
            result += uppalpha[lowalpha.find(ch)];
        }
    }
    return result;
}

int main() {
    string str = "GeEkSfOrGeEkS";
    string converted = toggleChar(str);
    cout << converted << endl;
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* toggleChar(char* input) {
    char uppalpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char lowalpha[] = "abcdefghijklmnopqrstuvwxyz";
    int len = strlen(input);
    
    char* output = (char*)malloc((len + 1) * sizeof(char));
    if (output == NULL) {
        return NULL; 
    }
    
    // Iterate over each character in the input string
    for (int i = 0; i < len; i++) {
        char ch = input[i];
        
        // If character is uppercase, find its position
        // and get the corresponding lowercase
        if (strchr(uppalpha, ch)) {
            int j = strchr(uppalpha, ch) - uppalpha;
            output[i] = lowalpha[j];
        } else {
            int j = strchr(lowalpha, ch) - lowalpha;
            output[i] = uppalpha[j];
        }
    }
    output[len] = '\0';  
    return output;
}

int main() {
    char str[] = "GeEkSfOrGeEkS";

    char* toggled = toggleChar(str);
    printf("%s\n", toggled);
        

    return 0;
}
Java
public class GFG {

    public static String toggleChar(String str) {
        String result = "";
        String uppalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String lowalpha = "abcdefghijklmnopqrstuvwxyz";
        
        // Iterate over each character in the input string
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            
            // If character is uppercase, find its position
            // and get the corresponding lowercase
            if (uppalpha.indexOf(ch) != -1) {
                result += lowalpha.charAt(uppalpha.indexOf(ch));
            } else {
                result += uppalpha.charAt(lowalpha.indexOf(ch));
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String str = "GeEkSfOrGeEkS";
        String toggled = toggleChar(str);
        System.out.println(toggled);
    }
}
Python
def toggleChar(s):
    uppalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    lowalpha = "abcdefghijklmnopqrstuvwxyz"
    result = ""
    # Iterate over each character in the input string
    for i in s:
        
         # If character is uppercase, find its position
         # and get the corresponding lowercase
        if i in uppalpha:
            result += lowalpha[uppalpha.index(i)]
        else:
            result += uppalpha[lowalpha.index(i)]
    return result

if __name__ == "__main__":
    str = "GeEkSfOrGeEkS"
    x = toggleChar(str)
    print(x)
C#
using System;

public class GFG{
    public static string ToggleChar(string str){
        string uppalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string lowalpha = "abcdefghijklmnopqrstuvwxyz";
        string result = "";
        
        // Iterate over each character in the input string
        for (int i = 0; i < str.Length; i++){
            char ch = str[i];
            
            // If character is uppercase, find its position
            // and get the corresponding lowercase
            if (uppalpha.IndexOf(ch) != -1){
                result += lowalpha[uppalpha.IndexOf(ch)];
            }
            else{
                result += uppalpha[lowalpha.IndexOf(ch)];
            }
        }

        return result;
    }

    public static void Main(string[] args){
        string str = "GeEkSfOrGeEkS";
        string x = ToggleChar(str);
        Console.WriteLine(x);
    }
}
JavaScript
function toggleChar(str) {
    let result = "";
    let uppalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let lowalpha = "abcdefghijklmnopqrstuvwxyz";
    
    // Iterate over each character in the input string
    for (let i = 0; i < str.length; i++) {
        let ch = str[i];
    
        // If character is uppercase, find its position
        // and get the corresponding lowercase and vice versa
        if (uppalpha.indexOf(ch) !== -1) {
            result += lowalpha[uppalpha.indexOf(ch)];
        } else {
            result += uppalpha[lowalpha.indexOf(ch)];
        }
    }

    return result;
}

// Driver Code
let str = "GeEkSfOrGeEkS";
let x = toggleChar(str);
console.log(x);

Output
gEeKsFoRgEeKs

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

The main logic is to 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.

ASCII values of alphabets: A - Z = 65 to 90 and a - z = 97 to 122 

Step By Step Implementation :

  1. Take one string of any length and calculate its length.
  2. Scan string character by character and keep checking the index. 
  3. If a character in an index is in lower case, then subtract 32 to convert it into upper case, else add 32 to convert it in lowercase
C++
#include <iostream>
using namespace std;

string toggleChar(string &str) {
    int ln = str.length();

    // Conversion according to ASCII values
    for (int i = 0; i < ln; i++) {
        if (str[i] >= 'a' && str[i] <= 'z')
        
            // Convert lowercase to uppercase
            str[i] = str[i] - 32;
        else if (str[i] >= 'A' && str[i] <= 'Z')
        
            // Convert uppercase to lowercase
            str[i] = str[i] + 32;
    }
    return str;
}

int main() {
    string str = "GeEkSfOrGeEkS";

    str = toggleChar(str);

    cout << str;
    return 0;
}
C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* toggleChar(char* str){
    int ln = strlen(str);
    char* result = (char*)malloc((ln + 1) * sizeof(char));

    // Conversion according to ASCII values
    for (int i = 0; i < ln; i++) {
        if (str[i] >= 'a' && str[i] <= 'z')

            // Convert lowercase to uppercase
            result[i] = str[i] - 32;
        else if (str[i] >= 'A' && str[i] <= 'Z')

            // Convert uppercase to lowercase
            result[i] = str[i] + 32;
        else
            result[i] = str[i]; 
    }

    result[ln] = '\0'; 
    return result;
}

int main(){
    char str[] = "GeEkSfOrGeEkS";

    char* toggled = toggleChar(str);

    printf("%s", toggled);

    return 0;
}
Java
public class GFG {

    public static String toggleChar(String str) {
        int ln = str.length();

        // Conversion according to ASCII values
        char[] arr = str.toCharArray();
        for (int i = 0; i < ln; i++) {
            if (arr[i] >= 'a' && arr[i] <= 'z')
            
                // Convert lowercase to uppercase
                arr[i] = (char)(arr[i] - 32);
            else if (arr[i] >= 'A' && arr[i] <= 'Z')
            
                // Convert uppercase to lowercase
                arr[i] = (char)(arr[i] + 32);
        }
        return new String(arr);
    }

    public static void main(String[] args) {
        String str = "GeEkSfOrGeEkS";

        str = toggleChar(str);

        System.out.println(str);
    }
}
Python
def toggleChar(str):
    ln = len(str)

    # Conversion according to ASCII values
    for i in range(ln):
        if str[i] >= 'a' and str[i] <= 'z':

            # Convert lowercase to uppercase
            str[i] = chr(ord(str[i]) - 32)

        elif str[i] >= 'A' and str[i] <= 'Z':

            # Convert lowercase to uppercase
            str[i] = chr(ord(str[i]) + 32)

if __name__ == "__main__":
    str = "GeEkSfOrGeEkS"
    str = list(str)

    toggleChar(str)

    str = ''.join(str)
    print(str)
C#
using System;
using System.Text;

class GFG {
    
    static string toggleChar(string str){
        int ln = str.Length;
        StringBuilder result = new StringBuilder(str);
        
        // Conversion according to ASCII values
        for (int i = 0; i < ln; i++){
            if (result[i] >= 'a' && result[i] <= 'z')

                // Convert lowercase to uppercase
                result[i] = (char)(result[i] - 32);

            else if (result[i] >= 'A' && result[i] <= 'Z')

                // Convert uppercase to lowercase
                result[i] = (char)(result[i] + 32);
        }

        return result.ToString();
    }
    
    public static void Main() {
        string str = "GeEkSfOrGeEkS";
        string toggled = toggleChar(str);
        Console.WriteLine(toggled);
    }
}
JavaScript
function toggleChar(str) {
  const chars = str.split('');
  const ln = chars.length;

  // Conversion according to ASCII values
  for (let i = 0; i < ln; i++) {
    const code = chars[i].charCodeAt(0);
    if (code >= 97 && code <= 122) {
        
      // Convert lowercase to uppercase (subtract 32)
      chars[i] = String.fromCharCode(code - 32);
    } else if (code >= 65 && code <= 90) {
        
      // Convert uppercase to lowercase (add 32)
      chars[i] = String.fromCharCode(code + 32);
    }
  }

  return chars.join('');
}

// Driver Code
const str = "GeEkSfOrGeEkS";
console.log(toggleChar(str));  

Output
gEeKsFoRgEeKs

[Approach 2] 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.

Step By Step Implementation :

  • Traverse the given string S.
  • For each character, Si, do Si =  Si^ (1 << 5).Si^ (1 << 5) toggles the 5thbit which means 97 will become 65 and 65 will become 97:
  • Print the string after all operations
C++
#include <iostream>
using namespace std;

string toggleChar(string& S) {
    string result = S;  
    
    // Iterate over the string in order to flip the 5th bit.
    for (auto& ch : result) {
        if (isalpha(ch)) {
            
            // Toggle the 5th bit to flip case
            ch ^= (1 << 5);  
        }
    }
    return result;
}

int main() {
    string S = "GeEkSfOrGeEkS";
    string toggled = toggleChar(S);  
    cout << toggled << endl;
    return 0;
}
C
#include <stdio.h>
#include <ctype.h>

char* toggleChar(char *S) {
    
    // Iterate over the string in order to flip the 5th bit.
    for (int i = 0; S[i] != '\0'; ++i) {
        if (isalpha((char)S[i])) {
            
             // Toggle the 5th bit to flip case
            S[i] ^= (1 << 5);  
        }
    }
    return S;  
}

int main(void) {
    char S[] = "GeEkSfOrGeEkS";
    char* toggled = toggleChar(S);  
    printf("%s\n", toggled);
    return 0;
}
Java
class GFG {

    static String toggleChar(String input) {
        
         // Convert string to char array
        char[] chars = input.toCharArray(); 
        
        // Iterate over the string in order to flip the 5th bit.
        for (int i = 0; i < chars.length; i++) {
            if (Character.isAlphabetic(chars[i])) {
                
                 // Toggle the 5th bit to flip case
                chars[i] ^= (1 << 5);  
            }
        }

        return new String(chars); 
    }

    public static void main(String[] args) {
        String S = "GeEkSfOrGeEkS";
        String toggled = toggleChar(S);  
        System.out.println(toggled);
    }
}
Python
def toggleChar(s):
    ans = ""
    
    # Iterate over the string in order to flip the 5th bit.
    for ch in s:
        
            # Toggle the 5th bit to flip case
            ans += chr(ord(ch) ^ (1 << 5))
    return ans


if __name__ == "__main__":
    s = "GeEkSfOrGeEkS"
    result = toggleChar(s)
    print(result)
C#
using System;

class GFG {
    static string toggleChar(string input){
        
        // Iterate over the string in order to flip the 5th bit.
        char[] chars = input.ToCharArray();
        for (int i = 0; i < chars.Length; i++) {
            if (char.IsLetter(chars[i])) {
                // Toggle the 5th bit to flip case
                chars[i] = (char)(chars[i] ^ (1 << 5));
            }
        }
        return new string(chars);
    }

    public static void Main(string[] args){
        string S = "GeEkSfOrGeEkS";
        string toggled = toggleChar(S);
        Console.WriteLine(toggled);
    }
}
JavaScript
function toggleChar(str) {
  const chars = str.split('');

  for (let i = 0; i < chars.length; i++) {
    const code = chars[i].charCodeAt(0);

    // Iterate over the string in order to flip the 5th bit.
    if ((code >= 65 && code <= 90) ||
    (code >= 97 && code <= 122)) {
        
      // Toggle the 5th bit to flip case
      chars[i] = String.fromCharCode(code ^ (1 << 5));
    }
  }

  return chars.join('');
}

// Driver code
const s = "GeEkSfOrGeEkS";
console.log(toggleChar(s));  

Output
gEEKcafeTERIA

[Approach 3] Library-Based Case Toggling - O(n) Time and O(1) 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.

C++
#include <iostream>
#include <cctype>
using namespace std;

string toggleChar(string& str) {
    string result = "";
    
    // Iterate over the original string
    for (int i = 0; i < str.length(); i++) {
        char ch = str[i];
        
        // Check the case of the character and
        // toggle accordingly
        if (isupper(ch))
            result += tolower(ch);
        else
            result += toupper(ch);
    }
    return result;
}

int main() {
    string str = "GeEkSfOrGeEkS";
    string x = toggleChar(str);
    cout << x << endl;
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

char* toggleChar(char* str) {
    int len = strlen(str);
    char* result = (char*)malloc(len + 1);
    
    // Iterate over the original string
    for (int i = 0; i < len; i++) {
        char ch = str[i];
        
        // Check the case of the character and
        // toggle accordingly
        if (isupper((unsigned char)ch))
            result[i] = tolower((unsigned char)ch);
        else
            result[i] = toupper((unsigned char)ch);
    }
    result[len] = '\0';
    return result;
}

int main() {
    const char* str = "GeEkSfOrGeEkS";
    char* x = toggleChar(str);
    printf("%s\n", x);
    free(x);
    return 0;
}
Java
public class GFG {

    public static String toggleChar(String str) {
        String result = "";
        
        // Iterate over the original string
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            
            // Check the case of the character and
            // toggle accordingly
            if (Character.isUpperCase(ch))
                result += Character.toLowerCase(ch);
            else
                result += Character.toUpperCase(ch);
        }
        return result;
    }

    public static void main(String[] args) {
        String str = "GeEkSfOrGeEkS";
        String x = toggleChar(str);
        System.out.println(x);
    }
}
Python
def toggleChar(str):
    result = ""
    
    # Iterate over the original string
    for i in range(len(str)):
        ch = str[i]
        
        # Check the case of the character and
        # toggle accordingly
        if ch.isupper():
            result += ch.lower()
        else:
            result += ch.upper()
    return result

if __name__ == "__main__":
    str = "GeEkSfOrGeEkS"
    x = toggleChar(str)
    print(x)
C#
using System;

class Program {
    static string toggleChar(string str) {
        string result = "";
        
        // Iterate over the original string
        for (int i = 0; i < str.Length; i++) {
            char ch = str[i];
            
            // Check the case of the character and
            // toggle accordingly
            if (char.IsUpper(ch))
                result += char.ToLower(ch);
            else
                result += char.ToUpper(ch);
        }
        return result;
    }

    static void Main() {
        string str = "GeEkSfOrGeEkS";
        string x = toggleChar(str);
        Console.WriteLine(x);
    }
}
JavaScript
function toggleChar(str) {
    let result = "";
    
    // Iterate over the original string
    for (let i = 0; i < str.length; i++) {
        const ch = str[i];
        
        // Check the case of the character and
        // toggle accordingly
        if (ch === ch.toUpperCase())
            result += ch.toLowerCase();
        else
            result += ch.toUpperCase();
    }
    return result;
}

// Driver Code
const str = "GeEkSfOrGeEkS";
const x = toggleChar(str);
console.log(x);

Output
gEeKsFoRgEeKs

[Approach 4] Using Transform Function - O(n) Time and O(1) Space

This implementation performs an in‑place pass over the string and, at each position, invokes std::transform on a single‑character iterator range—applying ::tolower or ::toupper—to toggle the case of that character using the STL’s functional algorithm.

Note :- The "Transform Function" is only available in C++.

C++
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;

string toggleChar(string str) {
    
    // Iterate over the string
    for (int i = 0; i < str.length(); i++) {
        
        // Check the case of character and
        // use transform function accordingly
        if (isupper(str[i])) {
            transform(str.begin() + i,
            str.begin() + i + 1, str.begin() + i, ::tolower);
        } else {
            transform(str.begin() + i,
            str.begin() + i + 1, str.begin() + i, ::toupper);
        }
    }
    return str;
}

int main() {
    string str = "GeEkSfOrGeEkS";
    string result = toggleChar(str);
    cout << result << endl;
    return 0;
}

Output
gEeKsFoRgEeKs

[Approach 5] Pointer Based Approach - O(n) Time and O(1) Space

The main logic is, obtain a raw pointer to the string’s internal buffer (&str[0]) and then walk it character by character until the null terminator, using the <cctype> predicates and converters (isupper/tolower and toupper) to flip each letter’s case in‑place.
Note :- We get pointer based approach in C and C++ only.

C++
#include <iostream>
#include <cctype>
#include <string>
using namespace std;

string toggleChar(string str) {
    
    // Point to the first character
    char* p = &str[0];  

    // Use pointer to traverse through the string
    // change uppercase character to lower case
    // and vice-versa
    while (*p != '\0') {
        if (isupper(static_cast<unsigned char>(*p))) {
            *p = tolower(static_cast<unsigned char>(*p));
        } else {
            *p = toupper(static_cast<unsigned char>(*p));
        }
        ++p;
    }
    return str;
}

int main() {
    string str = "GeEkSfOrGeEkS";
    str = toggleChar(str);
    cout << str << endl;
    return 0;
}
C
#include <stdio.h>
#include <ctype.h>
#include <string.h>

char* toggleChar(char* str) {
    
    // Point to the first character
    char* p = str;

    // Use pointer to traverse through the string
    // change uppercase character to lower case
    // and vice-versa
    while (*p != '\0') {
        if (isupper((unsigned char)*p)) {
            *p = tolower((unsigned char)*p);
        } else {
            *p = toupper((unsigned char)*p);
        }
        ++p;
    }
    return str;
}

int main() {
    char str[] = "GeEkSfOrGeEkS";
    printf("%s\n", toggleChar(str));
    return 0;
}

Output
gEeKsFoRgEeKs



CPP Program to Convert Lowercase to Uppercase & vice versa
Practice Tags :

Similar Reads