实验6-10 统计单词的长度 (15 分)

时间:2025-02-19 07:11:12

实验6-10 统计单词的长度 (15 分)

本题目要求编写程序,输入一行字符,统计每个单词的长度。所谓“单词”是指连续不含空格的字符串,各单词之间用空格分隔,空格数可以是多个。
输入格式:

输入给出一行字符。
输出格式:

在一行中输出每个单词的长度。每个数字后有一个空格。
输入样例:

How are you?
结尾无空行

输出样例:

3 3 4

#include<>
#include<>
typedef struct ListNode{
    char data;
    struct ListNode *next;
}ListNode;
int main(){
    ListNode *head=(ListNode *)malloc(sizeof(ListNode));
    ListNode *tail;
    head->next=NULL;
    tail=head;
    char ch;
    scanf("%c",&ch);
    head->data=ch;
    int sum=0;
     scanf("%c",&ch);
    while(ch!='\n'){
        ListNode *p=(ListNode *)malloc(sizeof(ListNode));
        p->data=ch;
        p->next=NULL;
        tail->next=p;
        tail=p;
        scanf("%c",&ch);
    }
    tail->next=NULL;
    ListNode *t=head;
   // printf("%c",t->data);
   int tag=0;
   int tag2=0;
    while(t){
        if(t->data!=' '){
        	tag=1;
        	//printf("%c",t->data);
            sum++;
            tag2=1;
        }
        else{
        	if(tag==1)
            	printf("%d ",sum);
            sum=0;
            tag=0;
        }
        t=t->next;
    }
    if(tag==1)
   	 printf("%d ",sum);
   	 if(tag2==0)
   	 	printf("%d ",tag2);
    return  0;
}