codescracker
c++

C++ Program to Count Number of Words in a String



« Previous Program Next Program »

In this article, you will learn and get code to count total number of words present or available in a given string by user at run-time in C++ language.

For example, if the entered string is, codes cracker dot com, then total number of words is 4.

Count Total Number of Words in String

To count the total number of words available in a string in C++ programming, you have to ask from user to enter the string or sentence first. And then count and print the result as shown in the program given below.

The question is, write a program in C++ that counts total number of words in a string. Here is its answer.

// C++ Program to Count Number of Words in a String
// ----codescracker.com----

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    char str[200];
    int i=0, chk=0, countWord=0;
    cout<<"Enter the String: ";
    gets(str);
    while(str[i]!='\0')
    {
        if(str[i]==' ')
        {
            if(chk!=0)
                countWord++;
            chk=0;
        }
        else
        {
            chk++;
        }
        i++;
    }
    if(chk!=0)
        countWord++;
    cout<<"\nTotal Number of Words = "<<countWord;
    cout<<endl;
    return 0;
}

This program was build and run under Code::Blocks IDE. Here is its sample run:

C++ program count number words sentence

Now supply any string say this is codes cracker dot com as input, and press ENTER key to count and print total number of words available in the entered string:

c++ count words in string

And here is another sample run with following user input:

  this    is codes cracker    dot com  
That is, __this____is_codes_cracker____dot_com__. In this string, there are 2, 4, 1, 1, 4, 1 spaces are available before each words, and 2 spaces after last word:

count words in string c++

The dry run of above program with user input, this is codes cracker dot com goes like:

C++ Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker