Home »
C++ Programs
C++ program to change the string to sentence case using class
Submitted by Shubh Pachori, on August 13, 2022
Problem statement
Given a string, we have to change its case to sentence case using the class and object approach.
Example:
Input:
Enter String: sHuBh
Output:
Sentence cased String: Shubh
C++ code to change the string to sentence case 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;
}
//sentanceCase() function is to manipulate
//the string
string sentanceCase() {
//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++) {
//condition for the first character
if (index == 0) {
//if the first character is a lowercase then
//it will converted to the uppercase
if (str[index] >= 'a' && str[index] <= 'z') {
temp_str[index] = str[index] - 32;
}
//else it will as it is copied
else {
temp_str[index] = str[index];
}
}
//if condition for whole string to check if there is any character
else if ((str[index] >= 'a' && str[index] <= 'z') || (str[index] >= 'A' && str[index] <= 'Z')) {
//if there is a uppercase character in middle of the
//string then it will be converted to lowercse
if (str[index] >= 'A' && str[index] <= 'Z') {
temp_str[index] = str[index] + 32;
}
//else it will copied as it is
else {
temp_str[index] = str[index];
}
}
//if it is not a character then it will copied as it is
else {
temp_str[index] = str[index];
}
}
//tranfering null
temp_str[index] = 0;
//return the edited string
return temp_str;
}
};
int main() {
//create a object
String S;
//declare a string variable to store the string
string s;
//object is calling getString() function to get the string
S.getString();
//sentanceCase() function is called by the
//object to manipulate it
s = S.sentanceCase();
cout << "Sentance cased String: " << s;
return 0;
}
Output
Enter String: includehelp
Sentance cased String: Includehelp
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 sentenceCase() 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 sentenceCase() member function to change the given string to sentence case. The sentenceCase () function contains the logic to change the given string to a sentence case and printing the result.
C++ Class and Object Programs (Set 2) »