Program to toggle all characters in a string

06 Jul, 2022
Given a string, the task is to toggle all the characters of the string i.e to convert Upper case to Lower case and vice versa.
Examples: 
Input  : gfg
Output : GFG

Input  : aBc12#
Output : AbC12#

Input  : tu@kmiNi
Output : TU@KMInI
Traverse the given string, if uppercase characters come, convert into lowercase and lowercase letter convert into uppercase.
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to toggle all characters#include<bits/stdc++.h>using namespace std; void toggleChars(char str[]){    for (int i=0; str[i]!='\0'; i++)    {        if (str[i]>='A' && str[i]<='Z')            str[i] = str[i] + 'a' - 'A';        else if (str[i]>='a' && str[i]<='z')            str[i] = str[i] + 'A' - 'a';    }} // Driver codeint main(){    char str[] = "GeKf@rGeek$";    toggleChars(str);    cout << "String after toggle " << endl;    cout << str << endl;    return 0;}
// Java program to toggle all characters class GFG{ static void toggleChars(char str[]){    for (int i=0; i<str.length; i++)    {        if (str[i]>='A' && str[i]<='Z')            str[i] = (char) (str[i] + 'a' - 'A');        else if (str[i]>='a' && str[i]<='z')            str[i] = (char) (str[i] + 'A' - 'a');    }} // Driver codepublic static void main(String[] args){    char str[] = "GeKf@rGeek$".toCharArray();    toggleChars(str);    System.out.println("String after toggle ");    System.out.println(String.valueOf(str));}} // This code is contributed by 29AjayKumar
# Python3 program to toggle all charactersdef toggleChars(str):     for i in range(len(str)):        if (str[i] >= 'A' and str[i] <= 'Z'):            str = str[:i] + chr(ord(str[i]) + \                     ord('a') - ord('A')) + str[i + 1:];        else if (str[i] >= 'a' and str[i] <= 'z'):            str = str[:i] + chr(ord(str[i]) + \                     ord('A') - ord('a')) + str[i + 1:];    return str; # Driver codestr = "GeKf@rGeek$";str = toggleChars(str);print(str);     # This code is contributed by 29AjayKumar
// C# program to toggle all charactersusing System;     class GFG{ static void toggleChars(char []str){    for (int i = 0; i < str.Length; i++)    {        if (str[i] >= 'A' && str[i] <= 'Z')            str[i] = (char) (str[i] + 'a' - 'A');        else if (str[i] >= 'a' && str[i] <= 'z')            str[i] = (char) (str[i] + 'A' - 'a');    }} // Driver codepublic static void Main(String[] args){    char []str = "GeKf@rGeek$".ToCharArray();    toggleChars(str);    Console.WriteLine("String after toggle ");    Console.WriteLine(String.Join("",str));}} // This code is contributed by Princi Singh
<script> function toggleChars(str){    for (let i = 0; i < str.length; i++)    {        if (str[i] >= 'A' && str[i] <= 'Z')            str[i] =  String.fromCharCode(str[i].charCodeAt(0) + 'a'.charCodeAt(0) - 'A'.charCodeAt(0));        else if (str[i] >= 'a' && str[i] <= 'z')            str[i] =  String.fromCharCode(str[i].charCodeAt(0) + 'A'.charCodeAt(0) - 'a'.charCodeAt(0));    }} let str = "GeKf@rGeek$".split("");toggleChars(str);document.write("String after toggle ");document.write((str).join("")); // This code is contributed by rag2127.</script>
String after toggle 
gEkF@RgEEK$
Time complexity: O(n), where n is length of stringAuxiliary space: O(1)
We can use the Bitwise XOR operation to toggle all the characters in given string
As we know the ascii value of small and capital char case is differ by just 1 bit (5th bit). We can simply toggle that bit to toggle the char case of a string.
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to toggle all characters#include<bits/stdc++.h>using namespace std; void toggleChars(char str[]){    for (int i=0; str[i]!='\0'; i++)    {        if (isalpha(str[i])) {          str[i] = (char)(str[i]^(1<<5));        }    }} // Driver codeint main(){    char str[] = "GeKf@rGeek$";      cout << "String before toggle " << endl;      cout << str << endl;    toggleChars(str);    cout << "String after toggle " << endl;    cout << str << endl;    return 0;} // This code is contributed by @kaustubhvats08
// Java program to toggle all characters class GFG{ static void toggleChars(char str[]){    for (int i=0; i<str.length; i++)    {        if (Character.isAlphabetic(str[i])) {            str[i] = (char)(str[i]^(1<<5));        }    }} // Driver codepublic static void main(String[] args){    char str[] = "GeKf@rGeek$".toCharArray();    System.out.println("String before toggle ");    System.out.println(String.valueOf(str));    toggleChars(str);    System.out.println("String after toggle ");    System.out.println(String.valueOf(str));}} // This code is contributed by @kaustubhvats08
# Python3 program to toggle all charactersdef toggleChars(s):    for i in range(len(s)):      if s[i].isalpha():        s = s[:i] + str(chr(ord(s[i])^(1<<5))) + s[i+1:]    return s; # Driver codes = "GeKf@rGeek$";print("String before toggle")print(s)s = toggleChars(s);print("String after toggle")print(s);     # This code is contributed by @kaustubhvats08
// C# program to toggle all charactersusing System;     class GFG{ static void toggleChars(char []str){    for (int i = 0; i < str.Length; i++)    {        if (Char.IsLetter(str[i])){          str[i] = (char)(str[i]^(1<<5));        }    }} // Driver codepublic static void Main(String[] args){    char []str = "GeKf@rGeek$".ToCharArray();    Console.WriteLine("String before toggle ");    Console.WriteLine(String.Join("",str));    toggleChars(str);    Console.WriteLine("String after toggle ");    Console.WriteLine(String.Join("",str));}} // This code is contributed by @kaustubhvats08
<script> function toggleChars(str){    for (let i = 0; i < str.length; i++)    {        if ((/[a-zA-Z]/).test(str[i])){            str[i] = (String.fromCharCode((str[i].charCodeAt(0)^(1<<5))));        }    }} let str = "GeKf@rGeek$".split("");document.write("String before toggle ");document.write((str).join(""));toggleChars(str);document.write("String after toggle ");document.write((str).join("")); // This code is contributed by @kaustubhvats08.</script>
String before toggle 
GeKf@rGeek$
String after toggle 
gEkF@RgEEK$
Time complexity: O(n), where n is length of stringAuxiliary space: O(1)
This article is contributed by MATHE_KA_BANDA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
29AjayKumar
princi singh
AakashYadav4
rag2127
sweetyty
kaustubhvats08
surinderdawra388
shaheeneallamaiqbal
hardikkoriintern
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.