《编程思维与实践》1029.字符排序
题目

思路
桶排序的思想,考虑到调用qsort进行排序时是直接移动指针,那么数组中非字母字符的相对位置其实会发生改变,那就不能连带着非字母字符一起排,故可以考虑将去除大写字母和空格的字符串存在一个数组(桶)里并排好序, 同时再记录哪个位置存储着非字母(包括空格),输出时判断该位置是否为非字母即可.
代码
int cmp(const void *a,const void *b) //qsort是会直接将指针移到后面,那么非字符的相对位置就也会发生变化
{
char *m=(char*)a;
char *n=(char*)b;
return *m-*n;
}
int main()
{
int T;
scanf("%d",&T);
getchar();
for(int i=0;i<T;i++)
{
char s[201]; //读取字符串
char s1[201]; //去除非大写字母和空格
int pos[201]={0}; //记录存储位置哪里为非字母 非字母地方记为1
gets(s);
int k=0,r=0;
for(int j=0;j<strlen(s);j++)
{
if(s[j]>='A'&&s[j]<='Z')
{
s1[k]=s[j];
k++;
}
else
{
pos[j]=1;
}
}
s1[k]='\0';
qsort(s1,strlen(s1),sizeof(char),cmp);
printf("case #%d:\n",i);
int temp=0;
for(int j=0;j<strlen(s);j++)
{
if(pos[j]==1)
{
printf("%c",s[j]);
}
else{
printf("%c",s1[temp]);
temp++;
}
}
printf("\n");
}
return 0;
}