句中最长的单词

输入一个英文句子,长度不超过40个字符。编写程序,输出句子中最长的一个单词。Input长度不超过40的字符串Output句中最长的单词Sample Input
This is a test sentence
Sample Output
sentence
Hint1.输入只有一个句子,不需使用while 
2.若句尾有标点,则标点和最后一个单词可看成是一个单词,可以不用作额外判断 
3.假设句中最长的单词只有一个
#include<stdio.h>
#include<stdlib.h>
  
char* findmax(char s[]){
    char* longest_word;
 longest_word = (char*)malloc(41);//分配空间,如果没有这个,会runtime,也可以将其写为全局变量
    int max=0, word_length=0, p=0, i=0;
    for(i=0; s[i]!='\0'; i++){
        if(s[i] == ' '){
            if(max < word_length){
                max = word_length;
                p = i; 
            }
            word_length = 0;
        }
        else{
            word_length++;
        }
    }
    if(max < word_length){
        max = word_length;
        p = i;
    }
    for(p=p-max,i=0; max>0; max--,p++,i++){
        longest_word[i] = s[p];
    }
    longest_word[i] = '\0';
    return longest_word;
}
int main(){
    char s[41];

   while(gets(s))
/*while((c = getchar()) != '\n' && c != EOF )
   s[i++] = c;*/
{
    char* longest_word = findmax(s);
    printf("%s\n", longest_word);
     free(longest_word);}
     return 0;
}

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

#define N 200
char s[N + 1], max[N + 1];

int main(void)
{
    char *p;
    int maxlen, len;

    while(gets(s) != NULL) {
        maxlen = 0;
        max[0] = '\0';
        p = strtok(s, " ");
        while(p) {
            len = strlen(p);
            if(len >= maxlen) {
                maxlen = len;
                strcpy(max, p);
            }
            p = strtok(NULL, " ");
        }

        printf("%s\n", max);
    }

    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值