Home »
C++ Programs
C++ program to find the length of a string using class
Submitted by Shubh Pachori, on August 06, 2022
Problem statement
Given a string, we have to find the length of a string using class using the class and object approach.
Example:
Input:
Enter String: Length of the string.
Output:
Length of the string is 21
C++ code to find the length of a string using class and object approach
#include <iostream>
using namespace std;
// create a class
class String {
// private data member
private:
char string[30];
// public functions
public:
// putString() function to store the string
void putString() {
cout << "Enter String:";
cin.getline(string, 30);
}
// length() function to find its length
int length() {
// int type variable for indexing
int index;
// for loop to find the length of the string
for (index = 0; string[index]; index++)
;
// returning the length
return index;
}
};
int main() {
// create a object
String S;
// declaring int type variable to store the length
int l;
// calling puString() function to store the string
S.putString();
// calling length() function to find the length of the string
l = S.length();
cout << "Length of the string is " << l;
return 0;
}
Output
RUN 1:
Enter String:Hello, world!
Length of the string is 13
RUN 2:
Enter String:Don't Wait for Opportunity, Create it.
Length of the string is 29
Explanation
In the above code, we have created a class String, one char type array data member string[30] to store the string, and public member functions putString() and length() to store and find the length of the given string.
In the main() function, we are creating an object S of class String, reading a string by the user using the putString() function, and finally calling the length() member function to find the length of the given string. The length() function contains the logic to find the length of the given string and printing the result.
C++ Class and Object Programs (Set 2) »