c语言字符数组怎么按姓氏的首字母排序
比如有两个字符数组:张三、李四,将其排序为李四、张三
要按照姓氏的首字母对字符数组进行排序,可以使用C语言中的标准库函数qsort
和自定义的比较函数。
以下是一个示例代码,演示如何按照姓氏的首字母对字符数组进行排序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 自定义的比较函数,用于比较两个字符串的姓氏首字母
int compare(const void *a, const void *b) {
const char *str1 = *(const char **)a;
const char *str2 = *(const char **)b;
// 提取姓氏的首字母
char surname1 = str1[0];
char surname2 = str2[0];
// 比较姓氏的首字母
if (surname1 < surname2) {
return -1;
} else if (surname1 > surname2) {
return 1;
} else {
return 0;
}
}
int main() {
char *names[] = {"张三", "李四", "王五", "赵六"};
int numNames = sizeof(names) / sizeof(names[0]);
// 使用qsort函数对字符数组进行排序
qsort(names, numNames, sizeof(names[0]), compare);
// 打印排序后的结果
for (int i = 0; i < numNames; i++) {
printf("%s\n", names[i]);
}
return 0;
}
在这个示例中,我们使用了qsort
函数对names
字符数组进行排序。qsort
函数需要传入要排序的数组指针,数组中元素的个数,每个元素的大小以及一个比较函数。我们自定义了compare
函数,用于比较两个字符串的姓氏首字母。
运行这个示例代码,将输出按照姓氏首字母排序后的结果:
这个示例代码假设每个字符串都包含一个姓氏和一个名字,并且姓氏始终以一个字符表示。如果你的实际需求不同,你可能需要修改compare
函数以适应你的字符串格式。
我可以给你一个使用C语言实现字符串排序的示例代码。
思路:
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUM 100 // 假设最多有100个字符串
#define MAX_LEN 20 // 字符串最大长度为20
void bubbleSort(char *arr[], int n);
int main()
{
char *names[MAX_NUM]; // 用指针数组存储字符串
char str[MAX_LEN];
int n = 0; // 用来记录字符串个数
// 输入字符串并存储到指针数组中
printf("请输入要排序的字符串,按回车结束输入:\n");
while (fgets(str, MAX_LEN, stdin) != NULL && n < MAX_NUM)
{
str[strcspn(str, "\n")] = '\0'; // 去掉输入的换行符
names[n] = (char *)malloc(strlen(str) + 1); // 为每个字符串分配内存
strcpy(names[n], str); // 复制字符串到对应指针所指的内存中
n++; // 字符串个数加1
}
// 对名字按照姓氏首字母进行排序
bubbleSort(names, n);
// 输出排序后的字符串数组
printf("\n排序后的字符串为:\n");
for (int i = 0; i < n; i++)
{
printf("%s\n", names[i]);
free(names[i]); // 释放每个字符串所占的内存
}
system("pause");
return 0;
}
void bubbleSort(char *arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j][0] > arr[j + 1][0]) // 按照姓氏首字母的ascii码进行比较
{
char *temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
在该代码中,我们使用了冒泡排序算法进行字符串排序,并且使用了指针数组来存储多个字符串,通过遍历指针数组来进行排序和输出。