本题要求用函数实现。main函数主要负责输入输出,从键盘输入一行字符,‘,’ ‘.’ '!'及空格、TAB键均应看成是单词间隔符。自定义函数longestWord求得这行字符中的最长单词,然后在main函数中输出此单词。 如果有多组单词长度符合要求,输出第一次出现的那个。
#include <stdio.h>int fun(const char *str, char *word){ int max = 0, count = 0; int i = 0, j, k; while (str[i]) { if (str[i] == ',' || str[i] == '.' || str[i] == '!' || str[i] == ' ' || str[i] == '\t') { k = 0; if (max < count) { max = count; for (j = i - count; j < i; j++) word[k++] = str[j]; word[k] = '\0'; } count = 0; } else count++; i++; } return max;}int main(){ char s[100], word[100]; int pos; gets(s); printf("max = %d\n", fun(s, word)); puts(word); return 0;}
#include <stdio.h>void fun(char *s) { char *p = s; int i,pos,npos,maxlen = 0,len; while(*p) { npos = p - s; len = 0; while((*p != ',') && (*p != '.') && (*p != ' ') && (*p != '!') && (*p)) { len++; p++; } if(len > maxlen) { maxlen = len; pos = npos; } if(*p) p++; } printf("最长的单词是 : "); for(i = 0;i < maxlen;i++) putchar(s[pos + i]); putchar('\n');}int main() { char s[1024]; printf("请输入一个串 : "); gets(s); fun(s); return 0;}