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


题目描述

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

输入格式:

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

输出格式:

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

输入样例:

red yellow blue green white

输出样例:

After sorted:
blue
green
red
white
yellow

#include <iostream>
#include <algorithm>
#include <string>

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;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM