编写一个程序通过指针变量按字符串的长度对三个字符串从大到小排序,要求将这三个字符串存储在一个二维数组中。
法一:
#include “stdio.h”
#include “conio.h”
#include “string.h”
#define M 3
#define MAXLEN 25
void main( )
{char s[M][MAXLEN],p[MAXLEN];
int i,j;
printf(“Please input some strings:\n”);
for(i=0;i<M;i++)scanf(“%s”,s[i]);
printf(“The original strings are as follows:\n”);
for(i=0;i<M;i++) printf(“%s\n”,s[i]);
for(i=0;i<M;i++)
for(j=i+1;j<M;j++)
if(strlen(s[i])<strlen(s[j]))
{strcpy(p,s[i]);strcpy(s[i],s[j]);strcpy(s[j],p);}
printf(“The sorted strings are as follows:\n”);
for(i=0;i<M;i++) printf(“%s\n”,s[i]);
getch();
}
程序的执行结果是
Please input some strings:
That is right
The original strings are as follows:
That
is
right
The sorted strings are as follows:
right
That
is
法二:
#include “stdio.h”
#include “conio.h”
#include “string.h”
#define M 3
#define MAXLEN 25
void sort(char str[][MAXLEN],int k)
{int i,j;
char p[MAXLEN];
for(i=0;i<k;i++)
for(j=i+1;j<k;j++)
if(strlen(str[i])<strlen(str[j]))
{strcpy(p,str[i]);strcpy(str[i],str[j]);strcpy(str[j],p);}
}
void main( )
{char s[M][MAXLEN],p[MAXLEN];
int i,j;
printf(“Please input some strings:\n”);
for(i=0;i<M;i++)scanf(“%s”,s[i]);
printf(“The original strings are as follows:\n”);
for(i=0;i<M;i++) printf(“%s\n”,s[i]);
sort(s,M);
printf(“The sorted strings are as follows:\n”);
for(i=0;i<M;i++) printf(“%s\n”,s[i]);
getch();
}
程序的执行结果是
Please input some strings:
wqet sdfgh 345zx
The original strings are as follows:
wqet
sdfgh
345zx
The sorted strings are as follows:
sdfgh
345zx
wqet
暂无评论内容