用C语言将4个学生的姓名按拼音首字母从大到小排序并显示.
发布网友
发布时间:2023-04-23 23:03
我来回答
共1个回答
热心网友
时间:2023-10-10 11:40
一个学生的这样搞:
姓名分开,成两个字符串。
分别排序,形成新的字符串,然后输出。
其他学生一样的方法。
#include <stdio.h>
#include <string.h>
#define STU_NAME_MAX_LEN 20
char stu_name[][STU_NAME_MAX_LEN] =
{
"iker cassilas",
"luis suarez",
"cristiano ronaldo",
"lionl messi"
};
void main()
{
int stu_count = sizeof(stu_name)/sizeof(stu_name[0]);
int i, j, k;
for (i=0; i<stu_count; i++)
{
char firstname[STU_NAME_MAX_LEN];
char familyname[STU_NAME_MAX_LEN];
int blankpos = 0;
//将姓名分开
memset(firstname, 0, STU_NAME_MAX_LEN);
memset(familyname, 0, STU_NAME_MAX_LEN);
for (j=0; j<sizeof(stu_name[i]); j++)
{
if (stu_name[i][j] == ' ')
{
blankpos = j;
break;
}
}
memcpy(firstname, &stu_name[i][0], blankpos);
memcpy(familyname, &stu_name[i][blankpos+1], sizeof(stu_name[i])-blankpos-1);
printf("old: %s %s\n", firstname, familyname);
//排序
for (j=0; firstname[j]!='\0'; j++)
{
for (k=j+1; firstname[k]!='\0'; k++)
{
if (firstname[j] < firstname[k])
{
char ctemp = firstname[j];
firstname[j] = firstname[k];
firstname[k] = ctemp;
}
}
}
for (j=0; familyname[j]!='\0'; j++)
{
for (k=j+1; familyname[k]!='\0'; k++)
{
if (familyname[j] < familyname[k])
{
char ctemp = familyname[j];
familyname[j] = familyname[k];
familyname[k] = ctemp;
}
}
}
printf("new:%s %s\n\n", firstname, familyname);
}
}