有三個英文字符組成的字符串,要求按照字母的順序輸出。
註:「三個英文字符」此處理解為「三個英文單詞/字符串」。
char *p[],排序時交換指針而非移動字符串內容,效率高。strcmp (字典序)。#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp_str(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
char *words[] = {"delta", "alpha", "epsilon"}; // 三個單詞
int n = sizeof(words) / sizeof(words[0]);
qsort(words, n, sizeof(char *), cmp_str);
printf("按字母序排序後:\n");
for (int i = 0; i < n; i++) {
puts(words[i]);
}
return 0;
}
void sort_str_ptr(char *p[], int n) {
int i, j;
char *tmp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - 1 - i; j++) {
if (strcmp(p[j], p[j + 1]) > 0) {
tmp = p[j];
p[j] = p[j + 1];
p[j + 1] = tmp;
}
}
}
}
按字母序排序後:
alpha
delta
epsilon
| 技術點 | 代碼體現 | 注意事項 |
|---|---|---|
| 指針數組 | char *words[] = {...} | 存儲字符串首地址,排序時僅交換 4/8 字節指針 |
| strcmp 比較 | strcmp(s1, s2) | 返回 <0, 0, >0 分表 s1 |
| qsort 回調 | cmp_str 強轉 const char** | 參數是元素地址,元素類型為 char*,故雙重指針 |
| 字符串常量 | "alpha" 存放在只讀區 | 指針數組指向常量區,**不可修改內容** (如 p[0][0]='A' 會崩潰) |
char words[][20] = {"delta", "alpha", "epsilon"}; // 二維數組,內容可改
// 排序時需交換整行內容 (strcpy) 或用索引數組間接排序
對少量字符串排序,**指針數組 + strcmp + qsort/冒泡** 是標準範式:代碼簡潔、避免大量內存搬移、利用庫函數保證正確性。掌握「指針數組間接排序」思想,可輕鬆擴展至結構體、大數據量等場景。