C语言,编写一个程序,输入若干字符串,找出其中最长的字符串并输出。要用指针数组存放这些字符串,并要结合函数实现。求思路以及代码,谢谢
1、我们在main函数之前定义一个函数。
2、然后我们就可以开始编写,并且先输入整个框架。
3、然后我们可以用和循环开始进行输出。
4、利用普通变量也可以使用指针变量来书写。
5、在这里我们将以指针变量来书写。
6、书写完毕后,我们将可回去main函数中进行直接调用。
因为字符串一般是以‘\0’为结尾,据此写一个循环,每循环一次,就看看该次数的字符是否为'\0'。若发现是\0,就把本次循环的次数返回。此时循环的次数就是字符串的长度。
得到字符长度就好办了,直接将字符长度进行比较,看那个长就输出行了呗~
int strcmp(char *s,char *t)
{
for(;*s&&*t&&*s++==*t++;);
return(*s-*t);
}
#include<stdio.h>
#include<malloc.h>
#include<string.h>
int main()
{char *p[20];
int n,i,max=0,maxi=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i]=(char *)malloc(20);
scanf("%s",p[i]);
if(strlen(p[i])>max)
{
max=strlen(p[i]);
maxi=i;
}
}
printf("\n%s\n",p[maxi]);
return 0;
}
本回答被网友采纳