Program to count word in a sentence
Input : Takes a string and count the number of words in the input string.
Example:
Input: Welcome to C++
Output: Total number of words in a sentence is 3
Algorithm
- Create a string, find its length
- Start loop from i=0 to i< length
- Increment the count variable if empty space is encountered(‘ ‘)
- Print the number of words in the sentence as count+1 (number of words is 1 greater than number of spaces).
Code:
// C++ Program To Count Word in a Sentence
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{
char str[100];
int i, len, count = 0;
cout << "Write a sentence : ";
gets(str);
len = strlen(str);
for (i = 0; i < len; i++)
{
if (str[i] == ' ')
{
count++;
}
}
cout << "Total number of words in a sentence is " << count + 1;
return 0;
}
Report Error/ Suggestion