本题要求编写程序,读入5个字符串,按由小到大的顺序输出。
输入格式:
输入为由空格分隔的5个非空字符串,每个字符串不包括空格、制表符、换行符等空白字符,长度小于80。
输出格式:
按照以下格式输出排序后的结果:
After sorted:
每行一个字符串
输入样例:
red yellow blue green white
输出样例:
After sorted:
blue
green
red
white
yellow
代码一:
#include<stdio.h>
#include<string.h>
#define N 85
#define M 5
int main()
{
int i, j, t;
int len1[M] = { 0 };
int len2;
char str[M][N] = {'0'};
char ch;
char temp[N];
for (i = 0; i < M; i++)
{
ch = getchar();
for (j = 0; ch != ' '; j++)
{
str[i][j] = ch;
len1[i]++;
ch = getchar();
if (ch == '\n')
{
break;
}
}
}
for (i = 0; i < M-1; i++)
{
t = i;
for (j = i+1; j < M; j++)
{
if (strcmp(str[t], str[j])>0)
{
t = j;
}
}
strcpy(temp, str[i]);
strcpy(str[i], str[t]);
strcpy(str[t], temp);
}
printf("After sorted:\n");
for (i = 0; i < M; i++)
{
printf("%s", str[i]);
printf("\n");
}
return 0;
}
代码二:
#include <stdio.h>
#include <string.h>
int main (){
char a[5][80];char b[1][80];
int i;
for(i=0;i<5;i++) {
scanf("%s",a[i]);
}
int j;
for(i=0;i<5;i++){
for(j=i+1;j<5;j++){
if(strcmp(a[i],a[j])>0){
strcpy(b[0],a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],b[0]);
}}}
printf("After sorted:\n");
for(i=0;i<5;i++)
printf("%s\n",a[i]);
}
代码三:
int main(){
char *pstr[5];
for(int i=0; i<5; i++){
pstr[i] = (char *)malloc(sizeof(char)*81);
scanf("%s", pstr[i]);
}
char *tps = (char *) malloc(sizeof(char)*81);
for(int i=0; i<5; i++){
for(int j=i; j>0 && strcmp(pstr[j], pstr[j-1])<0; j--){
strcpy(tps, pstr[j-1]);
strcpy(pstr[j-1], pstr[j]);
strcpy(pstr[j], tps);
}
}
printf("After sorted:\n");
for(int i=0; i<5; i++) printf("%s\n", pstr[i]);
for(int i=0; i<5; i++) free(pstr[i]);
free(tps);
return 0;
}