Here is a C++ program to count the number of words in a string. In this C++ program, we will count the number of words in a sentence. Words are separated by one or multiple space characters.
For Example :Input Sentence: I love C++ programming Word Count : 4
To find the number of words in a sentence, we will first take a string input from user and store it in a character array(string). Here we are using strtok function of
strtok Function
- The function char *strtok(char *str, const char *delimiters); breaks string str into tokens, which are sequences of contiguous characters separated by any of the characters of string delimiters.
- First call to strtok function expects a C string as argument str, and returns first token. Subsequent calls of strtok function expects a null pointer argument and returns next word. strtok function is widely use to tokenize a string into words.
C++ Program to Count Words in Sentence
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char string[100], *token;
int count = 0;
cout << "Enter a string\n";
cin.getline(string, 100);
token = strtok(string, " ");
while(NULL != token)
{
count++;
token = strtok(NULL, " ");
}
cout << "Word Count : "<<count;
return 0;
}
Output
Enter a string I love C++ programming Word Count : 4
Recommended Posts