Program to Toggle all Characters in a String

Difficulty Level Easy
Frequently asked in Capgemini InfoEdge MAQ Oxigen Wallet

Problem Statement

In the “Program to Toggle all Characters in a String” problem we have given a string, write a program to toggle all characters of the given string. Here toggle means converting all the uppercase characters to lowercase and all lowercase characters to uppercase characters.

Input Format

The first line containing string s.

Output Format

Print the final string in one line.


  • 1<=|s|<=10^6.
  • s[i] is any special char or upper, lower case alphabet.



Explanation: Here we traverse the whole string char by char. Check for upper, lower case alphabet and change it accordingly. So, the final string after visiting all the char is “aBCD2#bcdA”.

Algorithm for Toggle all Characters in a String

  1. Take input the given string s.
  2. Traverse the whole string.
  3. Check if s[i] is an upper case alphabet then convert it into a lower case alphabet.
  4.  Else if s[i] is a lower case alphabet then convert it into an upper case alphabet.
  5. Else do nothing, just leave it.


C++ Program to Toggle all Characters in a String

#include <bits/stdc++.h>
using namespace std;

int main()
   string a;
   int n=a.length();
   for(int i=0;i<n;i++)
       if(a[i]>='A' && a[i]<='Z')
       else if(a[i]>='a' && a[i]<='z')
   return 0;

Java Program to Toggle all Characters in a String

import java.util.Scanner;

class sum { 
    public static void main(String[] args) 
        Scanner sr= new Scanner(;
        String s=;
        int n = s.length(); 
        char ans[] = s.toCharArray();
        for(int i=0;i<n;i++)
            if(ans[i]>='A' && ans[i]<='Z') 
                ans[i] = (char) (ans[i]+32);
            else if(ans[i]>='a' && ans[i]<='z') 
                ans[i] = (char) (ans[i]-32); 
        for(int i=0;i<n;i++)

Complexity Analysis for Toggle all Characters in a String

Time Complexity

O(n) where n is the size of the given string. Here we just traverse the whole string and perform some operations in constant time.

Space Complexity

o(1) because we don’t use any extra space to perform the operation.


Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions