C 練習實例79

C 語言經典100例 C 語言經典100例

題目:字串排序。

程式分析:無。

程式源代碼:

實例

// Created by www.xuhuhu.com on 15/11/9. // #include<stdio.h> #include<stdlib.h> #include <string.h> void swap(char*str1,char*str2); int main() { char str1[20],str2[20],str3[20]; printf("請輸入3個字串,每個字串以回車結束!:\n"); fgets(str1, (sizeof str1 / sizeof str1[0]), stdin); fgets(str2, (sizeof str2 / sizeof str2[0]), stdin); fgets(str3, (sizeof str3 / sizeof str3[0]), stdin); if(strcmp(str1,str2)>0)swap(str1,str2); if(strcmp(str2,str3)>0)swap(str2,str3); if(strcmp(str1,str2)>0)swap(str1,str2); printf("排序後的結果為:\n"); printf("%s\n%s\n%s\n",str1,str2,str3); return 0; } void swap(char*str1,char*str2) { char tem[20]; strcpy(tem,str1); strcpy(str1,str2); strcpy(str2,tem); }

以上實例運行輸出結果為:

請輸入3個字串,每個字串以回車結束!:
b
a
t
排序後的結果為:
a
b
t

C 語言經典100例 C 語言經典100例