Home »
C++ Programs
C++ program to change the string from uppercase to lowercase using class
Submitted by Shubh Pachori, on August 05, 2022
Problem statement
Given a string, we have to change it from uppercase to lowercase using class and object approach.
Example:
Input:
Enter String: ShUbH
Output:
Lowercased String: shubh
C++ code to change the string from uppercase to lowercase using class and object approach
#include <iostream>
using namespace std;
// create a class
class String {
// private data member
private:
char str[30];
// public functions for string manipulation
public:
// getString() functiom is to get the string
void getString() {
cout << "Enter String:";
cin >> str;
}
// lowercase() function is to
// manipulate the string
string lowercase() {
// declaring variables for operations
char temp_str[30];
int index;
// for loop to read the whole string and make changes in it
for (index = 0; str[index]; index++) {
// if condition to check if the
// character is in uppercase
if (str[index] >= 'A' && str[index] <= 'Z') {
// if the character is in uppercase then
// it will be converted to lowercase
temp_str[index] = str[index] + 32;
}
// else it will copied as it is
else {
temp_str[index] = str[index];
}
}
// return the edited string
return temp_str;
}
};
int main() {
// create an object
String S;
// declare a string variable to store the string
string s;
// object is calling getString() function to get the string
S.getString();
// lowercase() function is called by the object to manipulate it
s = S.lowercase();
cout << "Lowercased String:" << s;
return 0;
}
Output
RUN 1:
Enter String:AmItY
Lowercased String:amity
RUN 2:
Enter String:HeLLo
Lowercased String:hello
Explanation
In the above code, we have created a class String, one char type array data member str[30] to store the string, and two public member functions getString() and lowercase() 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 lowercase() member function to change the case from uppercase to the lowercase of the given string. The lowercase() function contains the logic to change the case of the given string and printing the result.
C++ Class and Object Programs (Set 2) »