C语言实现对英文的12个月份按字母进行排序
//
// @author: 冲哥
// @date: 2021/6/3 20:38
// @description:C语言实现对英文的12个月份按字母进行排序
// 公众号:C语言中文社区
#include <stdio.h>
#include <string.h>
#define NUM 12
void sort(char *months[]);
int main(){
char **p;
char *month[]={"January","February","March","April","May","June","July","August","September","October","November","December"};
printf("排序前:");
for (int i = 0; i < NUM; i++) {
printf("%s ", month[i]);
}
printf("\n");
p = month;
sort(p);
printf("排序后:");
for (int i = 0; i < NUM; i++) {
printf("%s ", month[i]);
}
printf("\n");
return 0;
}
void sort(char *months[]){
char *temp;
for (int i = 0; i < NUM; i++) {
for (int j = i+1; j < NUM; j++) {
if(strcmp(months[i],months[j]) > 0){
temp = months[i];
months[i] = months[j];
months[j] = temp;
}
}
}
}
公众号:C语言中文社区
这个实例中,我们使用到了二级指针,并将二级指针作为函数参数。作比较时使用到了strcmp()
函数
这里简单说下这个函数
「函数原型」:int strcmp(const char* stri1,const char* str2); 用于对两个字符串进行比较(区分大小写)
「函数作用」:根据 ASCII 编码依次比较 str1 和 str2 的每一个字符,直到出现不到的字符,或者到达字符串末尾(遇见\0)
「函数返回值」: