Convert characters of a string to opposite case in C++

We are given a string of any length and the task is to convert the string having uppercase letters to lowercase letters and lowercase letters to uppercase letters.

For Example

Input − string str = ”Welcome To The Site!”

Output − wELCOME tO tHE sITE!

Explanation − converted the letters W, T, T, S to lowercase and letters e,l,c,o,m,e,o,,i,t,e to uppercase and it doesn’t perform any operations to the special characters.

Input − string str = ”HELLO”

Output − hello

Explanation − converted the letters H,E,L,L,E to lowercase.

This can be done using two different approaches

  • Using inbuilt functions provided by C++ to perform these operations and those are toLowerCase(char) and toUpperCase(char).

  • Through the logic, which we are implementing in the below program.

Approach used in the below program is as follows

  • Input the string of any length

  • Calculate the length of the string using the length() function that will return an integer value as per the number of letters in the string including the spaces.

  • The ASCII values of uppercase letters[A-Z] start with 65 till 90 and lowercase letters[a-z] starts with 97 till 122.

  • Start the loop which will compare each letter in a string. If a letter is in uppercase then add 32 to convert it to lowercase and if the letter is in lowercase then subtract 32 to convert it to uppercase.

  • Print the string.


 Live Demo

using namespace std;
void Convert_case(string &str){
   //calculate the length of a string
   int len = str.length();
   //converting lowercase to uppercase and vice versa
   for (int i=0; i<len; 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;
int main(){
   string str = "What’s Your Name?";
   cout<<"String before conversion is: "<<str;
   cout<<"\nString after conversion is: "<<str;
   return 0;


If we run the above code it will generate the following output −

String before conversion is − What’s Your Name?
String after conversion is &mius; wHAT’S yOUR nAME?