目录
输入多个字符串,输出最长字符串。要求定义并使用函数maxLenStr(),
1170:
题目描述
输入多个字符串,输出最长字符串。要求定义并使用函数maxLenStr(),
void maxLenStr(char *str[], int n, int *max)
{
从字符串数组str中找出最长的一个字符串,并将其下标存入形参指针max所指内存。
}
输入
输入有多行,每行一个字符串,每个字符串长度不超过80,输入最多不超过100行,用****作为结束输入的标志,该行输入不用处理。
输出
输出最长的一个字符串。
答案:
# include<stdio.h>
# include<string.h>
# include<stdlib.h>
void maxLenStr(char *str[], int n, int *max);
int main()
{
char *str[100],s[81];
int i=0,max=0;
while(gets(s))//gets(s),s!="****"
if(strcmp(s,"****")!=0)
{
str[i++]=(char *)malloc(sizeof(char)*81);/*malloc 函数返回的是 void * 类型,强制转换为char型,
函数的实参为 sizeof(char) ,用于指明一个字符数据需要的大小。
*81代表长度 */
strcpy(str[i-1],s);
}
else
break;
maxLenStr(str,i,&max);
return 0;
}
void maxLenStr(char *str[], int n, int *max)
{
int i;
for(i=0; i<n; i++)
if(strlen(str[*max])<strlen(str[i]))
*max=i;
printf("%s\n",str[*max]);
}