习题8-7 字符串排序 (20分)

题目描述

本题要求编写程序,读入5个字符串,按由小到大的顺序输出。

输入格式:

输入为由空格分隔的5个非空字符串,每个字符串不包括空格、制表符、换行符等空白字符,长度小于80。

输出格式:

按照以下格式输出排序后的结果:
After sorted:
每行一个字符串

输入样例:

red yellow blue green white

输出样例:

After sorted:
blue
green
red
white
yellow

include

include

include

using namespace std;

int main()
{
string str[6];
cin >> str[0] >> str[1] >> str[2] >> str[3] >> str[4];
sort(str,str+5); //尾地址的下一个地址
cout << "After sorted:" << endl;
for(int i=0;i<5;i++)
cout << str[i] << endl;

return 0;
}


include <stdio.h>

include <string.h>

int main(void)
{
char ch[5][80];
int i,j;
for(i=0;i<5;i++)
{
scanf("%s",ch[i]);//亲测gets不行
}
for(i=0;i<4;i++)
{
for(j=0;j<4-i;j++)
{
if(strcmp(ch[j],ch[j+1])>0)//冒泡法排序,其他法当然也可以
{
char temp[80];
strcpy(temp,ch[j]);
strcpy(ch[j],ch[j+1]);
strcpy(ch[j+1],temp);//字符串跟数字、字符不同噢
}
}
}
printf("After sorted:\n");
for(i=0;i<5;i++)
{
puts(ch[i]);
}
return 0;
}

posted @ 2020-05-08 13:42  是羊驼呀  阅读(1599)  评论(0)    收藏  举报