×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to reverse the string using class

Submitted by Shubh Pachori, on August 08, 2022

Problem statement

Given a string, we have to reverse it using the class and object approach.

Example:

Input:
Enter String: amity

Output:
Reversed String: ytima

C++ code to reverse a string using 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 store string
  void getString() {
    cout << "Enter String:";
    cin >> str;
  }

  // reverse() function to reverse the string
  string reverse() {
    // initialising variables to perform operations
    char temp_str[30];
    int index_1, index_2, end;

    // for loop to find the length of the string
    for (end = 0; str[end]; end++)
      ;

    // for loop to reverse the string and copy it in another string
    for (index_1 = end - 1, index_2 = 0; index_1 >= 0; index_1--, index_2++) {
      temp_str[index_2] = str[index_1];
    }

    // transfering null
    temp_str[index_2] = 0;

    // returning the reversed string
    return temp_str;
  }
};

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

  // declare a string type variable to store string
  string s;

  // calling getString() function to insert string
  S.getString();

  // calling reverse() function to reverse the string
  s = S.reverse();

  cout << "Reversed String:" << s;

  return 0;
}

Output

Enter String:IncludeHelp
Reversed String:pleHedulcnI

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 reverse() to store and reverse the given string.

In the main() function, we are creating an object S of class String, reading the string given by the user using the getString() function, and finally calling the reverse() member function to reverse the given string. The reverse() function contains the logic to reverse the given string and printing the result.

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

Comments and Discussions!

Load comments ↻





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