C program to find total number of words in a string:
Steps:
1.Create a string array[]
2.Set Count=0
3.Take Input Using gets()
(We are not using scanf() ,because scanf() will not take words after blank space).
4.Use for loop
5.Start loop with i=0
6.Increment i until i ! = '\0' (last character of string).
7.Increment count
8.Print count+1
(We are printing count +1 because in end of the string, their is no blank space, their is '\0',therefore count will not increment by its own)
#include <stdio.h> #include <string.h> void main() { char ch[200]; int count=0,i; printf("Enter string:"); gets(ch); for (i = 0;ch[i] != '\0';i++) { if(ch[i] == ' ' && ch[i+1] != ' ') count++; } printf("Total Number of words are %d",count+1); }
Output :
Enter string:Thank to visit codingexpert10 Total Number of words are 4 Process returned 27 (0x1B) execution time : 42.452 s Press any key to continue.
Explaination:
Create an array first and then input the string. In this program, we are using the gets() function. If we use the scanf() function then the string after the blank space will not input() in the array. That is why we are using the gets () function. Create a variable named count and initialize it to zero. Make a for loop and put a condition in it that the loop will run until the last character '\ 0' comes.
Put condition in for loop if ch[i ] = ' ' and ch[i+1] ! =' ' if the condition satisfy increment count by one.
Then print count+1.
More Explaination:
//coming soon
Related programs:
0 Comments
Thanks,To visit this blog.