本實例輸入 3 個字符串,使用冒泡排序思想(兩兩比較交換)按字典序從小到大排序並輸出。
strcmp 比較字符串大小。swap 函數交換兩字符串內容(需臨時數組)。// Created by www.runoob.com on 15/11/9.
// Copyright © 2015年 菜鳥教程. All rights reserved.
//
#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");
gets(str1);
gets(str2);
gets(str3);
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
qsort 或標準排序算法。gets()。