Home »
C++ Programs
C++ program to reverse every word of a string using class
Submitted by Shubh Pachori, on September 08, 2022
Problem statement
Given a string, we have to reverse every word of a string using the class and object approach.
Example:
Input:
Enter String : who is there
Output:
Reverse : ohw si rehte
C++ code to reverse every word of a string using the class and object approach
#include <bits/stdc++.h>
using namespace std;
// create a class
class String {
// private data member
private:
string str;
// public member functions
public:
// getString() function to store string
void getString() {
cout << "Enter String: ";
getline(cin, str);
}
// reverseCharacter() function to
// reverse character in the string
string reverseCharacter() {
// initialising int type variables
// to perform operations
int length, index_1, index_2 = 0;
// calculating length of inputted string
length = str.size();
// for loop to reverse the words of the string
for (index_1 = 0; index_1 < length; index_1++) {
// if condition for spaces
if (str[index_1] == ' ') {
reverse(str.begin() + index_2, str.begin() + index_1);
index_2 = index_1 + 1;
}
// else if condition for last word
else if (index_1 == length - 1) {
reverse(str.begin() + index_2, str.end());
}
}
// returning the string
return str;
}
};
int main() {
// create an object
String S;
// string variable to store
// the string
string str;
// calling getString() function to
// input string
S.getString();
// calling reverseCharacter() function
// to reverse character
str = S.reverseCharacter();
cout << "Reverse : " << str << endl;
return 0;
}
Output
RUN 1:
Enter String: Hello World!
Reverse : olleH !dlroW
RUN 2:
Enter String: Welcome at IncludeHelp
Reverse : emocleW ta pleHedulcnI
Explanation
In the above code, we have created a class String, one string type data members str to store the string, and public member functions getString() and reverseCharacter() to store the string and to reverse every character of every word of the string.
In the main() function, we are creating an object S of class String, reading the inputted string by the user using getString() function, and finally calling the reverseCharacter() member function to reverse every character of every word of the string. The reverseCharacter() function contains the logic to reverse every character of every word of the string and printing the result.
C++ Class and Object Programs (Set 2) »