Home » Technical Interview Questions » String Interview Questions » Program to toggle all characters in a string

Program to toggle all characters in a string


Reading Time - 1 mins

Given a string, write a function 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

Example

INPUT
s = “[email protected]

OUTPUT
“D[email protected]

Algorithm

1. Traverse the given string

2. If uppercase character appears convert it to lowercase character and viceversa

C++ Program

#include<bits/stdc++.h>
using namespace std;
 
void toggleAllChars(char s[])
{
    //Traversing the given string
    for (int i=0; s[i]!='\0'; i++)
    {
        if (s[i]>='A' && s[i]<='Z')
            s[i] = s[i] + 'a' - 'A';
        else if (s[i]>='a' && s[i]<='z')
            s[i] = s[i] + 'A' - 'a';
    }
}
 

int main()
{
    char s[] = "[email protected]";
    cout<<"Given String: "<<endl<<s<<endl;
    toggleAllChars(s);
    cout << "String after toggle: "<<endl;
    cout << s << endl;
    return 0;
}

Try It

 

READ  Top K Frequent Words
Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions