C++ program to convert characters of a string to opposite case using class

Given a string, we have to convert characters of a string to opposite case using the class and object approach.
Submitted by Shubh Pachori, on August 26, 2022

Example:

Input:
Enter String: sHuBh PaChOrI

Output:
Inverse cased String: ShUbH pAcHoRi

C++ code to convert characters of a string to opposite case using the class and object approach

#include <iostream>
using namespace std;

// create a class
class String {
  // private data member
  private:
    char str[30];

  // public functions
  public:
    // getString() function to get the string
    void getString() {
      cout << "Enter String:";
      cin.getline(str, 30);
    }

  // inverseCase() function to invert the case of string
  string inverseCase() {
    // char type array to store inverse case string
    char temp[30];

    // int type variable for indexing
    int index;

    // for loop for tracersing the whole string
    for (index = 0; str[index]; index++) {
      // if condition to check if it is a alphabet or not
      if ((str[index] >= 'a' && str[index] <= 'z') || (str[index] >= 'A' && str[index] <= 'Z')) {
        // if condition to check if it is in lowercase
        if (str[index] >= 'a' && str[index] <= 'z') {
          // then it is converted to uppercase
          temp[index] = str[index] - 32;
        }
        // else it is converted to lowercase
        else {
          temp[index] = str[index] + 32;
        }
      }
      // else it is copied as it is
      else {
        temp[index] = str[index];
      }
    }

    // transfering null temp string
    temp[index] = 0;

    // returning temp string
    return temp;
  }
};

int main() {
  // create an object
  String S;

  // function is called by the object 
  // to store the string
  S.getString();

  // string type variable to store 
  // the inverted string
  string str;

  // inverseCase() function is called by the object to 
  // inverse the case of the string
  str = S.inverseCase();

  cout << "Inverse cased String:" << str;

  return 0;
}

Output:

RUN 1:
Enter String: InVeRsE cAsE sTrInG 
Inverse cased String: iNvErSe CaSe StRiNg

RUN 2:
Enter String:Hello, world!
Inverse cased String:hELLO, WORLD!

Explanation:

In the above code, we have created a class String, one char type array data member str[30] to store the string, and public member functions getString() and inverseCase() to store and manipulate the given string.

In the main() function, we are creating an object S of class String, reading a string by the user using the function getString(), and finally calling the inverseCase() member function to change the given string to the inverse case. The inverseCase () function contains the logic to convert characters of a string to opposite cases and printing the result.

C++ Class and Object Programs (Set 2) »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.