您好,登錄后才能下訂單哦!
在 C 語言中,對字符串進(jìn)行排序可以通過幾種方法來實(shí)現(xiàn)
#include<stdio.h>
#include<string.h>
int
。這里我們使用 strcmp()
函數(shù):int compare_strings(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
// 定義字符串?dāng)?shù)組并初始化
char *str[] = {"apple", "banana", "cherry", "orange", "kiwi"};
int n = sizeof(str) / sizeof(str[0]);
qsort()
函數(shù)對字符串?dāng)?shù)組進(jìn)行排序。在這里,我們將 compare_strings
函數(shù)作為參數(shù)傳遞給 qsort()
: qsort(str, n, sizeof(char *), compare_strings);
for (int i = 0; i < n; i++) {
printf("%s\n", str[i]);
}
return 0;
}
完整代碼如下:
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
int compare_strings(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
char *str[] = {"apple", "banana", "cherry", "orange", "kiwi"};
int n = sizeof(str) / sizeof(str[0]);
qsort(str, n, sizeof(char *), compare_strings);
for (int i = 0; i < n; i++) {
printf("%s\n", str[i]);
}
return 0;
}
編譯并運(yùn)行此程序,您將看到按字母順序排序后的字符串?dāng)?shù)組。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。