Convert Lower Case Alphabets to Upper Case and Vice-Versa in String

Convert Lower Case Alphabets to Upper Case and Vice-Versa in String” is a basic problem of string data structure. Here, we are given a string of length ‘n’ and our task is to convert upper-case alphabets to lower-case and vice-versa. String might contain characters except alphabets too, so we need to ignore them.

Example:

INPUT:
HelpMeStudyBro
OUTPUT:
hELPmEsTUDYbRO

The steps to convert cases of alphabets are:

  1. Scan the complete string.
  2. If the character of string is upper-case alphabet, add 32 with it.
  3. If the character of string is lower-case alphabet, subtract 32 from it.

C++ Program to convert cases of alphabet is as follows:

#include<bits/stdc++.h>  
using namespace std;  
int main()
{  
    string str;  
    cout<<"Enter a string:\n";  
    cin>>str;  
    int size = str.length();  
    for(int i = 0; i < size; i++)  
    {  
        if(str[i]>='A' && str[i]<='Z')  
        {  
            str[i] = str[i] + 32;  
        }  
        else if(str[i]>='a' && str[i]<='z')  
        {  
            str[i] = str[i] - 32;  
        }  
    }  
    cout<<"\nString after converting cases of letters are:\n"<<str;  
}  

OUTPUT:
Enter a string: HelpMeStudyBro
String after converting cases of letters are: hELPmEsTUDYbRO
Time Complexity:
O(n), where n is the length of string.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *