C语言代码问题

C语言代码问题 写函数void MaxLenWord(char s[ ]),计算并输出串s中的最长单词。根据样例,编写主函数。
样例输入
2
It was rush hour and I was dashing to a train in New York City Grand
Here are two birds one is a swallow the other is sparrow
样例输出
dashing
swallow sparrow

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

void MaxLenWord(char s[]){
    char *p = s;
    int max=0;
    int currentWordLen;
    int index=0;
    int wordsIndex=0;
    char **words = (char**)malloc(sizeof(char*)*(int)strlen(s)*0.5+0.5);

    while(p!= 0x1){
      index = strcspn(p," ");
      words[wordsIndex] = (char*)malloc(sizeof(char)*index);
      memcpy(words[wordsIndex],p,index);
      words[wordsIndex][index] = 0;
      p = strchr(p,' ')+1;
      currentWordLen = strlen(words[wordsIndex++]);
      if(currentWordLen>max)
          max = currentWordLen;
    }

    for(int i=0;i<wordsIndex;i++){
        if(strlen(words[i]) == max)
            printf("%-*s",max+1,words[i]);
    }
}

int main(){
    int count;
    scanf("%d",&count);

    char **words = (char**)malloc(sizeof(char*)*count);
    for(int i=0;i<count;i++){
        setbuf(stdin, NULL);
        words[i] = (char*)malloc(sizeof(char)*100);
        scanf("%[^\n]",words[i],100);
    }

    for(int i=0;i<count;i++){
        MaxLenWord(words[i]);
        putchar('\n');
    }

    return 0;
}

温馨提示:答案为网友推荐,仅供参考
相似回答