Home »
C++ Programs
C++ program to count total words in the string using class
Submitted by Shubh Pachori, on August 25, 2022
Problem statement
Given a string, we have to count total words in the string using the class and object approach.
Example:
Input:
Enter String: "count words in string"
Output:
Total Words: 4
C++ code to count total words in the string 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 get the string
void getString() {
cout << "Enter String:";
cin.getline(str, 30);
}
// countWord() function to count words in the string
int countWord() {
// int type variables for operations
int index, word = 0;
// for loop for traversing the whole string
for (index = 0; str[index]; index++) {
// if condition for the first character
if (index == 0) {
// if condition to check if it is a alphabet
if ((str[index] >= 'a' && str[index] <= 'z') || (str[index] >= 'a' && str[index] <= 'z')) {
// the increment in the word of 1
word++;
}
}
// else if condition to check if it is a space at index
else if (str[index] == ' ') {
// increment in index of 1 to check next character
index++;
// if condition to check if it is a alphabet
if ((str[index] >= 'a' && str[index] <= 'z') || (str[index] >= 'A' && str[index] <= 'Z')) {
// increment in index of 1 to check next character
word++;
}
}
}
// returning the counted word
return word+1;
}
};
int main() {
// create an object
String S;
// function is called by the object
// to store the string
S.getString();
// int type variable to store counted words
int word;
// countWord() function is called by the object to
// find out the total words in the string
word = S.countWord();
cout << "Total Words:" << word;
return 0;
}
Output
RUN 1:
Enter String:Hello world
Total Words:2
RUN 2:
Enter String:Welcome come to the world!
Total Words:5
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 countWord() 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 countWord() member function to count total words in the string. The countWord() function contains the logic to count the total words in the string and printing the result.
C++ Class and Object Programs (Set 2) »