题目描述: 输入一个字符串,将此字符串中最长的单词输出。
#include<stdio.h>
//输入一个字符串,把最长的单词输出
int main() {
char a[1024];
int n;
int max_len = 0;//存储最大单词长度
int wlen = 0;//存储单词长度
int max_i[1024] = { 0 };//存储长度最大的单词的下标(可能有多个最大值,用数组存贮)
int ii = 0;//当前单词的下标
int i = 0, j = 0;
char c;
while (c = getchar()) {
if (i && (a[i - 1] == ' ' || c == '\n')) {
if (wlen > max_len)
{
max_len = wlen;
max_i[0] = ii;
n = 1;
}
else if (wlen == max_len)
{
max_i[n] = ii;
n++;
}
if (c == '\n') break;
ii = i;
wlen = 0;
}
if(c != ' ') wlen++;
a[i++] = c;
}
a[i] = '\0';
printf("最长的单词长度为:%d\n", max_len);
printf("输入的字符串最长的单词有:\n");
for (i = 0; i < n; i++) {
for (j = 0; j <= max_len; j++) {
printf("%c", a[max_i[i] + j]);
}
printf("\n");
}
return 0;
}