Open In App

Toggle case of a string using Bitwise Operators

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string, write a function that returns toggle case of a string using the bitwise operators in place.
In ASCII codes, character ‘A’ is integer 65 = (0100 0001)2, while character ‘a’ is integer 97 = (0110 0001)2. Similarly, character ‘D’ is integer 68 = (0100 0100)2, while character ‘d’ is integer 100 = (0110 0100)2.

As we can see, only sixth least significant bit is different in ASCII code of ‘A’ and ‘a’. Similar behavior can be seen in ASCII code of ‘D’ and ‘d’. Therefore, we need to toggle this bit for toggling case. 

Examples: 

Input : "GeekSfOrgEEKs"
Output : "gEEKsFoRGeekS"                  

Input : "StRinG"
Output : "sTrINg"

The ASCII table is constructed in such way that the binary representation of lowercase letters is almost identical of binary representation of uppercase letters.

Toggling Case:

The integer with 6th LSB as 1 is 32 (0010 0000). Therefore, bitwise XORing of a character with 32 will toggle the 6th LSB of character and hence, will toggle its case. If character is upper case, it will be converted to lower case and vice versa. 

Implementation:

C++




// C++ program to get toggle case of a string
#include <bits/stdc++.h>
using namespace std;
 
// tOGGLE cASE = swaps CAPS to lower
// case and lower case to CAPS
char *toggleCase(char *a)
{
    for(int i = 0; a[i] != '\0'; i++)
    {
         
        // Bitwise EXOR with 32
        a[i] ^= 32;
    }
    return a;
}
 
// Driver Code
int main()
{
    char str[] = "CheRrY";
    cout << "Toggle case: "
         << toggleCase(str) << endl;
    cout << "Original string: "
         << toggleCase(str) << endl;
    return 0;
}
 
// This code is contributed by noob2000


C




// C program to get toggle case of a string
#include <stdio.h>
 
// tOGGLE cASE = swaps CAPS to lower
// case and lower case to CAPS
char *toggleCase(char *a)
{
    for (int i=0; a[i]!='\0'; i++) {
 
        // Bitwise EXOR with 32
        a[i] ^= 32;
    }
 
    return a;
}
 
// Driver Code
int main()
{
    char str[] = "CheRrY";
    printf("Toggle case: %s\n", toggleCase(str));
    printf("Original string: %s", toggleCase(str));
    return 0;
}


Java




// program to get toggle case of a string
 
public class Test
{
     
    static int x=32;
     
    // tOGGLE cASE = swaps CAPS to lower
    // case and lower case to CAPS
    static String toggleCase(char[] a)
    {
        for (int i=0; i<a.length; i++) {
       
            // Bitwise EXOR with 32
            a[i]^=32;
        }
        return new String(a);
    }
     
    /* Driver program */
    public static void main(String[] args)
    {
        String str = "CheRrY";
        System.out.print("Toggle case: ");
        str = toggleCase(str.toCharArray());
        System.out.println(str);
         
        System.out.print("Original string: ");
        str = toggleCase(str.toCharArray());
        System.out.println(str);   
    }
}


Python3




# Python3 program to get toggle case of a string
x = 32;
 
# tOGGLE cASE = swaps CAPS to lower
# case and lower case to CAPS
def toggleCase(a):
 
    for i in range(len(a)):
 
        # Bitwise EXOR with 32
        a = a[:i] + chr(ord(a[i]) ^ 32) + a[i + 1:];
    return a;
 
# Driver Code
str = "CheRrY";
print("Toggle case: ", end = "");
str = toggleCase(str);
print(str);
 
print("Original string: ", end = "");
str = toggleCase(str);
print(str);
 
# This code is contributed by 29AjayKumar


C#




// C# program to get toggle case of a string
using System;
 
class GFG {
     
    // tOGGLE cASE = swaps CAPS to lower
    // case and lower case to CAPS
    static string toggleCase(char []a)
    {
        for (int i = 0; i < a.Length; i++)
        {
         
            // Bitwise EXOR with 32
            a[i] ^= (char)32;
        }
         
        return new string(a);
    }
     
    /* Driver program */
    public static void Main()
    {
        string str = "CheRrY";
        Console.Write("Toggle case: ");
        str = toggleCase(str.ToCharArray());
        Console.WriteLine(str);
         
        Console.Write("Original string: ");
        str = toggleCase(str.ToCharArray());
        Console.Write(str);
    }
}
 
// This code is contributed by nitin mittal.


Javascript




<script>
// program to get toggle case of a string 
x = 32;
 
// tOGGLE cASE = swaps CAPS to lower
// case and lower case to CAPS
function toggleCase(a)
{
    for (i = 0; i < a.length; i++)
    {
   
        // Bitwise EXOR with 32
        a[i] = String.fromCharCode(a[i].charCodeAt(0)^32);
    }
    return a.join("");;
}
 
/* Driver program */
var str = "CheRrY";
document.write("Toggle case: ");
str = toggleCase(str.split(''));
document.write(str);
 
document.write("<br>Original string: ");
str = toggleCase(str.split(''));
document.write(str); 
 
// This code is contributed by Princi Singh
</script>


Output

Toggle case: cHErRy
Original string: CheRrY

Time complexity: O(n) since one traversal of the string is required to complete all operations hence the overall time required by the algorithm is linear
Auxiliary Space: O(1) since no extra array is used so the space taken by the algorithm is constant

Thanks to Kumar Gaurav for improving the solution.

Similar Article : 
Case conversion of a string using BitWise operators in C/C++

 



Last Updated : 23 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads