Home »
C++ Programs
C++ program to sort the string of characters in ascending order using class
Submitted by Shubh Pachori, on September 05, 2022
Problem statement
Given a string of characters, we have to sort its characters in ascending order using the class and object approach.
Example:
Input:
Enter String : string
Output:
Sorted String is ginrst
C++ code to sort the string of characters in ascending order 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
// insert string
void getString() {
cout << "Enter String : ";
cin.getline(str, 30);
}
// sortAscending() function to sort
// the string in ascending order
string sortAscending() {
// initialising int type variables
// to perform operations
int index_1, index_2, temp, length;
// for loop to finding the length of
// the string
for (length = 0; str[length]; length++);
// decrement in the length of 1
length--;
// for loop to read the whole string
for (index_1 = 0; str[index_1]; index_1++) {
// for loop to compare characters of the string
for (index_2 = 0; index_2 < length - index_1; index_2++) {
// if condition to check if the next
// character is smaller than
// this then swapping takes place
if (str[index_2] > str[index_2 + 1]) {
// swapping character if character
// are not in the order
temp = str[index_2];
str[index_2] = str[index_2 + 1];
str[index_2 + 1] = temp;
}
}
}
// returning the sorted string
return str;
}
};
int main() {
// create an object
String S;
// string type variable to
// store the string
string str;
// function is called by the object
// to store the string
S.getString();
// sortAscending() function is called
// by the object to sort the string in
// ascending order
str = S.sortAscending();
cout << "Sorted String is " << str;
return 0;
}
Output
RUN 1:
Enter String : aabbcdxyzaghbaa
Sorted String is aaaaabbbcdghxyz
RUN 2:
Enter String : xyz pqr abc
Sorted String is abcpqrxyz
Explanation
In the above code, we have created a class String, one char type string data member str[30] to store the string, and public member functions getString() and sortAscending() to store the given string and to sort the string in ascending order.
In the main() function, we are creating an object S of class String, reading the string using the getString() function, and finally calling the sortAscending() member function to sort the given string. The sortAscending() function contains the logic to sort the given string in ascending order and printing the result.
C++ Class and Object Programs (Set 2) »