Program to count word in a sentence in C++
Written by
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 variable and prompt the user to enter a sentence.
- Find the length of the string using the
strlen()
function. - Initialize a counter variable to 0.
- Iterate over the string using a loop, starting from the first character and ending at the last character.
- Inside the loop, increment the counter variable if an empty space character (
' '
) is encountered. - After the loop, print the number of words in the sentence as the counter variable plus 1 (since the number of words is 1 greater than the 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;
}
Output
Input:
Write a sentence: The quick brown fox jumps over the lazy dog.
Output:
Total number of words in a sentence is 9