In this tutorial you will learn about the C Program to Count Total Number of Words in a String and its application with practical example.
C Program to Find First Occurrence of a Word in a String
In this tutorial, we will learn to create a C program that will Count Total Number of Words in a String in C programming
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- For loop in C programming.
- Conditional Statements in C programming.
What is a string?
As we all know the String is a collection of characters and words. The word is a collection of alphabets. For string, only one variable is declared which can store multiple values. The String can consist of all the typeable data it means Digits, Alphabets, Symbols, etc.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables for the program. 2. Taking the input string from the user. 3. Passing those variables to for loop. 4. Using conditional statements to count the number of words in string. 6. Printing the result numbers. 7. End the program. |
Count Total Number of Words in a String
In this program, first, we will take the input string from the user. Then we will count the word from the string entered by the user. Now to count, we will pass that string to a for loop for counting.
Let us take the example program from the below code to count words.
Program:-
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 |
/* * C Program to Count Number of Words in a String. */ #include <stdio.h> #include <string.h> void main() { //declaring the required variables for the program. char s[200]; int count = 0, i; //taking input string from the user for the program. printf("Enter the string:\n"); //scanning the input string by the user. scanf("%[^\n]s", s); /*passing that string from the user to the for loop to count words.*/ for (i = 0;s[i] != '\0';i++) { //increasing the value of count per word. if (s[i] == ' ' && s[i+1] != ' ') count++; } //printing the number of words entered from the user. printf("Number of words in given string are: %d\n", count + 1); } |
Output:-
In the above program, we have first initialized the required variable.
- s[200] = it will hold the string value.
- i = it will hold the integer value.
- Count = it will hold the integer value.
Input string from the user for the program.
Counting the word in the string.
Printing output number of the word.