Write a C program to count number of words in a string. Given an input string, we have to write a c code to count number of words in a string. The words in a string are separated by space(‘ ‘).
For example –
Example 1 –
Input String – I love webrewrite dot com
Output – 5
Example 2 –
Input String – I love webrewrite dot com
Output – 5
How to Count Number of Words in a String
Traverse a string and check if a current character is a space and next character is not a space then increment the count by 1.
1 2 3 4 5 6 7 8 |
//Traverse a string for(int i = 0; i < len; i++) { //Current character is space and next character is not a space if(str[i] ==' ' && str[i+1] != ' ') { count++; } } |
Let’s implement them through C code.
C Program to Count Number of Words in a String
In this programming example, I have written a c program to count number of words in a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <stdio.h> #include <string.h> int main() { char str[100]; //Input string printf("Enter a string (Max 100) \n"); fgets(str,100,stdin); int count = 1, len = strlen(str); //Traverse a string for(int i = 0; i < len; i++) { if(str[i] ==' ' && str[i+1] != ' ') { count++; } } printf("Number of words in a string is %d", count); return 0; } |
In this video tutorial, I have explained the logic of counting number of words in a string.