首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C 語言字典序排序:首字母大寫其餘小寫 + qsort 排序

     編輯:程式設計疑難解答

需求

輸入若干英文單詞,首字母轉大寫、其餘小寫,按字典序排序輸出。

完整程式碼

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int cmp(const void *a, const void *b) {
    return strcmp(*(char**)a, *(char**)b);
}

int main() {
    int n;
    printf("單詞數量: ");
    scanf("%d", &n);
    getchar(); // 吸收換行
    
    char **words = malloc(n * sizeof(char*));
    for (int i = 0; i < n; i++) {
        words[i] = malloc(100);
        fgets(words[i], 100, stdin);
        words[i][strcspn(words[i], "\n")] = '\0'; // 去除換行
        
        // 首字母大寫,其餘小寫
        if (words[i][0]) words[i][0] = toupper(words[i][0]);
        for (int j = 1; words[i][j]; j++) words[i][j] = tolower(words[i][j]);
    }
    
    qsort(words, n, sizeof(char*), cmp);
    
    for (int i = 0; i < n; i++) {
        printf("%s\n", words[i]);
        free(words[i]);
    }
    free(words);
    return 0;
}

關鍵點

  • qsort 比較函數接收 const void*,實際為 char**,需雙重解參考 *(char**)a。
  • toupper/tolower 需 <ctype.h>,處理非字母字元安全 (原樣返回)。
  • 記憶體管理:malloc/free 成對使用,避免洩漏。
  • 輸入緩衝:scanf 後 getchar() 吸收換行,否則首個 fgets 讀到空行。

測試輸出

單詞數量: 5
wORd
HellO
yEllow
she
APPLE
Apple
Hello
She
Word
Yellow
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved