C語(yǔ)言中可以使用庫(kù)函數(shù)strcmp
和qsort
來(lái)對(duì)字符串進(jìn)行排序。
strcmp
函數(shù)比較兩個(gè)字符串的大小,然后使用qsort
函數(shù)對(duì)字符串?dāng)?shù)組進(jìn)行排序。#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return strcmp(*(const char**)a, *(const char**)b);
}
int main() {
char *strings[] = {"hello", "world", "apple", "banana"};
int n = sizeof(strings) / sizeof(strings[0]);
qsort(strings, n, sizeof(char*), compare);
for (int i = 0; i < n; i++) {
printf("%s\n", strings[i]);
}
return 0;
}
這段代碼會(huì)對(duì)字符串?dāng)?shù)組strings
進(jìn)行排序,輸出結(jié)果為:
apple
banana
hello
world
#include <stdio.h>
#include <string.h>
void sortStrings(char *strings[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (strcmp(strings[i], strings[j]) > 0) {
char *temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
}
}
}
int main() {
char *strings[] = {"hello", "world", "apple", "banana"};
int n = sizeof(strings) / sizeof(strings[0]);
sortStrings(strings, n);
for (int i = 0; i < n; i++) {
printf("%s\n", strings[i]);
}
return 0;
}
這段代碼會(huì)對(duì)字符串?dāng)?shù)組strings
進(jìn)行排序,輸出結(jié)果為:
apple
banana
hello
world
無(wú)論是使用qsort
函數(shù)還是自定義排序函數(shù),都可以對(duì)字符串?dāng)?shù)組進(jìn)行排序。