使用qsort函数对字符串中的星期名称进行排序
星期名排序
使用qsort
函数对字符串中的星期名称进行排序,且输入的星期不重复,将输入字符串按逗号分割,然后根据周一到周日的顺序排序,最后将排序后的字符串重新组合回原字符串中,代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>// 定义星期名称的顺序
const char *weekdays[] = {"Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday", "Sunday"
};//全局字符串,可进行传参
char current_weekdays[100] = "Wednesday,Tuesday,Friday,Sunday,Saturday,Monday";// 比较函数,用于确定两个星期名称的顺序
int weekday_compare(const void *a, const void *b) {// 获取待比较的字符串指针const char *str1 = *(const char **)a;const char *str2 = *(const char **)b;int index1 = -1, index2 = -1;// 查找第一个字符串在weekdays中的索引for (int i = 0; i < 7; i++) {if (strcmp(str1, weekdays[i]) == 0) {index1 = i;break; // 找到后立即退出}}// 查找第二个字符串在weekdays中的索引for (int i = 0; i < 7; i++) {if (strcmp(str2, weekdays[i]) == 0) {index2 = i;break; // 找到后立即退出}}// 按索引顺序排序return index1 - index2;
}void qosort_weekdays(void) {char *tokens[7]; // 存储分割后的字符串指针int count = 0; // 实际分割的字符串数量// 使用strtok分割字符串char *token = strtok(current_weekdays, ",");while (token != NULL && count < 7) {tokens[count++] = token;token = strtok(NULL, ",");}// 使用qsort排序qsort(tokens, count, sizeof(char *), weekday_compare);// 重新组合排序后的字符串char temp[100] = "";for (int i = 0; i < count; i++) {strcat(temp, tokens[i]);if (i < count - 1) {strcat(temp, ",");}}// 将结果复制strcpy(current_weekdays, temp);
}int main() {qosort_weekdays();printf("Sorted: %s\n", current_weekdays); // 输出结果return 0;
}
输出结果如下: