Open In App
Related Articles

Program to toggle all characters in a string

Improve Article
Improve
Save Article
Save
Like Article
Like

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




// C program to toggle all characters
#include <stdio.h>
 
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 code
int main()
{
    char str[] = "GeKf@rGeek$";
    toggleChars(str);
    printf("String after toggle \n");
    printf("%s\n", str);
    return 0;
}


C++




// 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 code
int main()
{
    char str[] = "GeKf@rGeek$";
    toggleChars(str);
    cout << "String after toggle " << endl;
    cout << str << endl;
    return 0;
}


Java




// 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 code
public 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




# Python3 program to toggle all characters
def 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 code
str = "GeKf@rGeek$";
str = toggleChars(str);
print(str);
     
# This code is contributed by 29AjayKumar


C#




// C# program to toggle all characters
using 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 code
public 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


Javascript




<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>


Output

String after toggle 
gEkF@RgEEK$

Time complexity: O(n), where n is length of string
Auxiliary 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




// C program to toggle all characters
#include <stdio.h>
 
void toggleChars(char str[])
{
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] >= 65 && str[i] <= 90) {
            str[i] = (char)(str[i] ^ (1 << 5));
        }
    }
}
 
// Driver code
int main()
{
    char str[] = "GeKf@rGeek$";
    printf("String before toggle\n");
    printf("%s\n", str);
    toggleChars(str);
    printf("String after toggle\n");
    printf("%s\n", str);
    return 0;
}


C++




// 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 code
int 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




// 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 code
public 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




# Python3 program to toggle all characters
def 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 code
s = "GeKf@rGeek$";
print("String before toggle")
print(s)
s = toggleChars(s);
print("String after toggle")
print(s);
     
# This code is contributed by @kaustubhvats08


C#




// C# program to toggle all characters
using 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 code
public 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


Javascript




<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>


Output

String before toggle 
GeKf@rGeek$
String after toggle 
gEkF@RgEEK$

Time complexity: O(n), where n is the length of the string
Auxiliary space: O(1)

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.


Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 01 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials