Convert characters of a string to opposite case - GeeksforGeeks

16 Mar, 2022
Given a string, convert the characters of the string into opposite case,i.e. if a character is lower case then convert it into upper case and vice-versa. 
Examples: 
Input : geeksForgEeks
Output : GEEKSfORGeEKS

Input : hello every one
Output : HELLO EVERY ONE
ASCII values  of alphabets: A – Z = 65 to 90, a – z = 97 to 122 Steps: 
Take one string of any length and calculate its length.Scan string character by character and keep checking the index. If a character in an index is in lower case, then subtract 32 to convert it in upper case, else add 32 to convert it in lower casePrint the final string.
Take one string of any length and calculate its length.
Scan string character by character and keep checking the index. If a character in an index is in lower case, then subtract 32 to convert it in upper case, else add 32 to convert it in lower case
If a character in an index is in lower case, then subtract 32 to convert it in upper case, else add 32 to convert it in lower case
Print the final string.
C++
Java
Python3
C#
Javascript
// CPP program to Convert characters// of a string to opposite case#include <iostream>using namespace std; // Function to convert characters// of a string to opposite casevoid convertOpposite(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;    }} // Driver functionint main(){    string str = "GeEkSfOrGeEkS";     // Calling the Function    convertOpposite(str);     cout << str;    return 0;}
// Java program to Convert characters// of a string to opposite caseclass Test {     // Method to convert characters    // of a string to opposite case    static void convertOpposite(StringBuffer str)    {        int ln = str.length();         // Conversion using predefined methods        for (int i = 0; i < ln; i++) {            Character c = str.charAt(i);            if (Character.isLowerCase(c))                str.replace(i, i + 1,                            Character.toUpperCase(c) + "");            else                str.replace(i, i + 1,                            Character.toLowerCase(c) + "");        }    }     public static void main(String[] args)    {        StringBuffer str            = new StringBuffer("GeEkSfOrGeEkS");        // Calling the Method        convertOpposite(str);         System.out.println(str);    }}// This code is contributed by Gaurav Miglani
# Python3 program to Convert characters# of a string to opposite case # Function to convert characters# of a string to opposite casedef convertOpposite(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)         else if str[i] >= 'A' and str[i] <= 'Z':             # Convert lowercase to uppercase            str[i] = chr(ord(str[i]) + 32) # Driver codeif __name__ == "__main__":    str = "GeEkSfOrGeEkS"    str = list(str)     # Calling the Function    convertOpposite(str)     str = ''.join(str)    print(str) # This code is contributed by# sanjeev2552
// C# program to Convert characters// of a string to opposite caseusing System;using System.Text; class GFG{         // Method to convert characters    // of a string to opposite case    static void convertOpposite(StringBuilder 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] = (char)(str[i] - 32);                             else if(str[i]>='A' && str[i]<='Z')                             //Convert uppercase to lowercase                str[i] = (char)(str[i] + 32);        }    }         // Driver code    public static void Main()    {        StringBuilder str = new StringBuilder("GeEkSfOrGeEkS");        // Calling the Method        convertOpposite(str);        Console.WriteLine(str);        }}// This code is contributed by PrinciRaj1992
<script> // Function to convert characters// of a string to opposite casefunction convertOpposite(str){    var ln = str.length;     // Conversion according to ASCII values    for (var i = 0; i < ln; i++)    {        if (str[i] >= 'a' && str[i] <= 'z')            // Convert lowercase to uppercase            document.write(            String.fromCharCode(str.charCodeAt(i) - 32)            );        else if (str[i] >= 'A' && str[i] <= 'Z')            // Convert uppercase to lowercase            document.write(            String.fromCharCode(str.charCodeAt(i) + 32)            );    }} // Driver functionvar str = "GeEkSfOrGeEkS";     // Calling the Function    convertOpposite(str); </script>
gEeKsFoRgEeKs
Time Complexity: O(n) Note: This program can alternatively be done using C++ inbuilt functions – Character.toLowerCase(char) and Character.toUpperCase(char). 
Approach 2: The problem can be solved using letter case toggling. Follow the below steps to solve the problem:
Traverse the given string S.
For each character Si, do Si =  Si ^ (1 << 5).
Si ^ (1 << 5) toggles the 5th bit which means 97 will become 65 and 65 will become 97:65 ^ 32 = 9797 ^ 32 = 65 
65 ^ 32 = 97
97 ^ 32 = 65 
Print the string after all operations
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to toggle all characters#include<bits/stdc++.h>using namespace std;  // Function to toggle charactersvoid toggleChars(string &S){    for(auto &it : S){       if(isalpha(it)){         it ^= (1 << 5);       }    }}  // Driver codeint main(){    string S = "GeKf@rGeek$";    toggleChars(S);    cout << "String after toggle " << endl;    cout << S << endl;    return 0;} //Code contributed by koulick_sadhu
// Java program to toggle all charactersimport java.util.*; class GFG{     static char []S = "GeKf@rGeek$".toCharArray(); // Function to toggle charactersstatic void toggleChars(){    for(int i = 0; i < S.length; i++)    {        if (Character.isAlphabetic(S[i]))        {            S[i] ^= (1 << 5);        }    }}  // Driver codepublic static void main(String[] args){    toggleChars();    System.out.print("String after toggle " + "\n");    System.out.print(String.valueOf(S));}} // This code is contributed by Amit Katiyar
# python program for the same approachdef isalpha(input):        input_char = ord(input[0])                 # CHECKING FOR ALPHABET        if((input_char >= 65 and input_char <= 90) or (input_char >= 97 and input_char <= 122)):            return True        else:            return False # Function to toggle charactersdef toggleChars(S):   s = ""    for it in range(len(S)):       if(isalpha(S[it])):         s += chr(ord(S[it])^(1<<5))      else:         s += S[it]       return s # Driver codeS = "GeKf@rGeek$"print(f"String after toggle {toggleChars(S)}") # This code is contributed by shinjanpatra
// C# program to toggle all charactersusing System; class GFG{     static char []S = "GeKf@rGeek$".ToCharArray(); // Function to toggle charactersstatic void toggleChars(){    for(int i = 0; i < S.Length; i++)    {        if (char.IsLetter(S[i]))        {            S[i] = (char)((int)(S[i]) ^ (1 << 5));        }    }}  // Driver codepublic static void Main(String[] args){    toggleChars();    Console.Write("String after toggle " + "\n");    Console.Write(String.Join("", S));}} // This code is contributed by Princi Singh
<script>   function isalpha(input) {        var input_char = input.charCodeAt(0);                  // CHECKING FOR ALPHABET        if (          (input_char >= 65 && input_char <= 90) ||          (input_char >= 97 && input_char <= 122))        {              return true;          }          else          {              return false;          }   }  // Function to toggle charactersfunction toggleChars(S){var s = "";     for(var it = 0; it < S.length; it++)    {       if(isalpha(S.charAt(it)))       {         s += String.fromCharCode(S.charCodeAt(it)^(1<<5))        }       else{       s += S.charAt(it);       }    }    return s;}  // Driver codevar S = "GeKf@rGeek$";document.write( "String after toggle " +toggleChars(S));</script> // This code is contributed by Akshit Saxena
This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
princiraj1992
gfg_sal_gfg
sanjeev2552
jakubtrlicik
koulick_sadhu
akshitsaxenaa09
amit143katiyar
princi singh
surinderdawra388
shinjanpatra
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
C++ Classes and Objects
Operator Overloading in C++
Constructors in C++
Copy Constructor in C++
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
Python program to check if a string is palindrome or not