習題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