Count the number of words

In the given string, find the numbers of words in it. Words can be separated by space (or) new line (or) tab.

Example

Input string : “In the given string”

Output : 4

Time complexity : O(n)

Algorithm

a. Maintain flag, flag = 1 indicates that separator is seen.

b. flag = 0 indicates character in the word.

c. Initialize count = 0.

We increment count when previous flag = 1 and next flag = 0.

d. Return final count.

C++ Program

#include <bits/stdc++.h>

using namespace std;
 
// returns number of words in str
int CountOFWords(char *str)
{
    int flag = 0;
    //Initialize count = 0
    //flag = 0, space
    //flag = 1 character
    int count = 0;
    while(*str)
    {
        //If str is space or tab or new line, // flag is 1
        if (*str == ' ' || *str == 'n' || *str == 't')
            {
                flag = 0;
            }
        //Next after flag = 0 there is flag = 1
        else if (flag == 0)
        {
            flag = 1;
            ++count;
        }
        // Move to next character
        ++str;
    }
 
    return count;
}
 
//Main function
int main()
{
    char str[] = "In given string";
    cout<<CountOFWords(str);
    return 0;
}

Try It

 

Translate »