習題8-7 字串排序 (20分)
阿新 • • 發佈:2021-01-25
技術標籤:# 浙大版《C語言程式設計(第3版)》題目集c語言c++visual studio
本題要求編寫程式,讀入5個字串,按由小到大的順序輸出。
輸入格式:
輸入為由空格分隔的5個非空字串,每個字串不包括空格、製表符、換行符等空白字元,長度小於80。
輸出格式:
按照以下格式輸出排序後的結果:
After sorted:
每行一個字串
輸入樣例:
red yellow blue green white
輸出樣例:
After sorted:
blue
green
red
white
yellow
原始碼
#include<stdio.h>
#include<string.h>
#pragma warning(disable:4996)
//字串按ascii碼順序排序,用strcmp(比較)函式,和strcpy(賦值)函式
int main()
{
char str[5][81];//用二維陣列定義字串陣列
for (int i = 0; i < 5; i++)
{
scanf("%s", str[i]);//先輸入,不用&,str[i]本身就是地址
}
//排序,氣泡排序演算法,無非就是換成了字串
for (int i = 0; i < 5 - 1; i++)
{ //按ascii碼排序,如果前一個小於後一個,交換(就是氣泡排序)
for (int j = 0; j < 5 - i - 1; j++)
{
if (strcmp(str[j], str[j + 1]) > 0)
{
char temp[81] = "";
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
}
}
}
printf("After sorted:\n");
for (int i = 0; i < 5; i++)
{
puts (str[i]);
}
getchar();
getchar();
return 0;
}
***謝謝!!!