Word Count of String

This is the solution for counting the number of Words in given String in C++

#include <iostream>
#include<string.h>

using namespace std;

class WordCount
{
    string s;
    int counts;
public:
    WordCount()
    {
        counts=1;
    }
    void GetString();
    void ReadCount();
    void print();
};

void WordCount::GetString()
{
    cout << endl << "Type your text:" ;
    getline(cin,s);
}

void WordCount::ReadCount()
{
    if(s[0]==' ')
    {
        counts=1;
    }
    for(int i=1; i<s.length(); i++)
    {
        if(s[i]==' ')
        {
            if(s[i+1]==' ')
            {
                counts = counts ;
            }
            else
            {
                counts++;
            }
        }
    }
}

void WordCount::print()
{
    cout << endl << "The string you entered is: " ;
    cout << s ;
    cout << endl << "Word Count=" << counts << endl ;
}

int main()
{
    WordCount wc;
    wc.GetString();
    wc.ReadCount();
    wc.print();
    return 0;
}

No comments:

Post a Comment