输入一个英文句子,长度不超过40个字符。编写程序,输出句子中最长的一个单词。Input长度不超过40的字符串Output句中最长的单词Sample Input
2.若句尾有标点,则标点和最后一个单词可看成是一个单词,可以不用作额外判断
3.假设句中最长的单词只有一个
This is a test sentenceSample Output
sentenceHint1.输入只有一个句子,不需使用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;
}