ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

C program to read a string and print the length of the each word

In this program, we will learn how to count length of each word in a string in C language?

There are many string manipulation programs and string user defined functions, this is an another program in which we will learn to count the length of each word in given string.

In this exercise (C program) we will read a string, like "Hi there how are you?" and it will print the word length of each word like 2, 5, 3, 3, 4.

Input
Hi there how are you?Output
2, 5, 3, 3, 4

Program to count length of each word in a string in C

#include <stdio.h>
#define MAX_WORDS	10

int main()
{
	
	char text[100]={0}; // to store string
	int cnt[MAX_WORDS]={0}; //to store length of the words
	int len=0,i=0,j=0;
	
	//read string
	printf("Enter a string: ");
	scanf("%[^\n]s",text); //to read string with spaces
	
	while(1)
	{
		if(text[i]==' ' || text[i]=='\0')
		{
			//check NULL
			if(text[i]=='\0')
			{
				if(len>0)
				{
					cnt[j++]=len;
					len=0;
				}
				break; //terminate the loop
			}
			cnt[j++]=len;
			len=0;
		}
		else
		{
			len++;
		}		
		i++;
	}
	
	printf("Words length:\n");
	for(i=0;i<j;i++)
	{
		printf("%d, ",cnt[i]);
	}
	printf("\b\b \n"); //to remove last comma
	
	return 0;
}

Output

Enter a string: Hi there how are you?
Words length:
2, 5, 3, 3, 4

C String Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.