# Program to Toggle all Characters in a String

Difficulty Level Easy
Frequently asked in Capgemini InfoEdge MAQ Oxigen Wallet
StringViews 1169

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

## Constraints

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

## Example

`Abcd2#BCDa`
`aBCD2#bcdA`

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.

## Implementation

### C++ Program to Toggle all Characters in a String

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

int main()
{
string a;
cin>>a;
int n=a.length();
for(int i=0;i<n;i++)
{
if(a[i]>='A' && a[i]<='Z')
{
a[i]='a'+(a[i]-'A');
}
else if(a[i]>='a' && a[i]<='z')
{
a[i]='A'+(a[i]-'a');
}
}
cout<<a<<endl;
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(System.in);
String s= sr.next();
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++)
{
System.out.print(ans[i]);
}
System.out.println();
}
}```
`AbCd#aB12`
`aBcD#Ab12`

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

Reference

Translate »