Count the occurrence of words in a string

4 thoughts on “Count the occurrence of words in a string”

  1. Hi, I just read your code, but I cannot understand it. I just made a program that counts the number of words and sentences in a paragraph. Now, I would like to wirte a code for the word frequency (occurrence of words ).
    Can you help me?
    Here is the program so far:

    #include
    using namespace std;

    const int NMaxChars = 10000;
    typedef char Phrase1[NMaxChars];

    int WordsCounter(const Phrase1 phrase);
    int SentencesCounter (const Phrase1 phrase);

    int main()
    {
    Phrase1 Phrase2;

    cout << “Type or paste a paragraph and press ENTER: “;
    cin.getline(Phrase2, NMaxChars);

    cout << “Word Count: ” << WordsCounter(Phrase2) << endl;
    cout << “Sentence Count: ” << SentencesCounter(Phrase2);

    return 0;
    }

    int WordsCounter(const Phrase1 phrase)
    {
    int n = 0;
    int index = 0;
    int len = strlen(phrase);

    while (index < len)
    {

    while ( phrase[index] == ‘ ‘ ) // gets index to the next character different from a blank space or to the end.
    index++;

    if (index < len) //if index is less than len, a new word starts.
    n++;

    while ( phrase[index] != ‘ ‘ ) //gets index to the next blank space or to the end.
    index++;

    }

    return n;
    }

    int SentencesCounter(const Phrase1 phrase)

    {
    int n = 0;
    int index = 0;
    int len = strlen(phrase);

    while (index < len)
    {

    while ( phrase[index] == ‘.’ ) // gets index to the next character different from a period or to the end.
    index++;

    if (index < len) //if index is less than len, a new word starts.
    n++;

    while ( phrase[index] != ‘.’ ) //gets index to the next period or to the end.
    index++;

    }

    return n;
    }

    Thanks in advance for your help,

    Andrea.

  2. thanks alot just for assisting every body to develop his programing concept with practise using such kinds of source code keep it up it is a good job.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s