Answer to Question #281247 in C for Tanya

Question #281247

Anbu had got lots of homework and he have to do it fast. So, he wants your help Can u help him? The problem is to find the length of the last word in the given string



Input: My Business is my Business None of your Business



Output: 8

1
Expert's answer
2021-12-20T10:02:02-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS