题解 | 字符串排序
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
char s[1010] = {0}, t[1010] = {0};
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
int count = 0;
// 提取字母
for (int i = 0; s[i] != '\0'; i++)
{
if (isalpha(s[i]))
t[count++] = s[i];
}
// 字母排序 使用稳定的冒泡排序
for (int i = 0; i < count - 1; i++)
{
for (int j = 0; j < count - 1 - i; j++)
{
if (tolower(t[j]) > tolower(t[j + 1]))
{
char temp = t[j];
t[j] = t[j + 1];
t[j + 1] = temp;
}
}
}
// 输出
int k = 0;
for (int i = 0; s[i] != '\0'; i++)
{
if (isalpha(s[i]))
printf("%c", t[k++]);
else
printf("%c", s[i]);
}
return 0;
}
将需要排序的字母提出来,然后对字母使用稳定排序(因为不要求比大小写),之后再按照原样输出就行
查看11道真题和解析