C Program to Count Total Number of Words in a String

Ex: Write a C program to count total number of words in a string. How to  count total number of words in a string. C Program to count total number of words in a string.

Input from user:

Enter the string:
This is codeforhunger.com

Expected output:

Number of words are: 3


    Required Knowledge:




  Step by step logic of the given program:

1. Accept string from user declare varible say str.

2. Run while loop till end of the string.

3. Inside the while loop check whether the current character is space or new line using:
if(str[i]== ' '||str[i]=='\n')
{
count++;
}

4. After that Print value of  count on the output screen.




  Program to count total number of words in a string:


#include<stdio.h>
#include<string.h>

void main()
{
char str[100];//declare string of max size 100
int i=0,count=1;

printf("Enter the string:\n");
gets(str);

/*Iterate loop till end of string*/ while(str[i]!='\0')
{
/* check whether the current character is space or new line*/
if(str[i]== ' '||str[i]=='\n')
{
count++;
}
i++;
}
printf("Number of words are:%d",count);
}


Above program shows the following output:


C Program to count total number of words in a string




No comments:

Post a Comment

If you have any doubts, please discuss here...👇