题解 | #字符串排序#

字符串排序

https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584

#include <stdio.h>
#include <stdlib.h> // 包含isalpha()函数的头文件
#include <ctype.h>  // 包含qsort()函数的头文件


//比较两个字符并忽略大小写的函数
int compare(const void* a, const void* b)
{
    // 将参数转换为 char指针并解引用, 将两个字符都转换为小写, 然后相减得到差值
    return tolower(*(char*)a) - tolower(*(char*)b);
}

int main()
{
    char str[1000], alp[1000]; // 输入字符串, 排序字符串
    int id, len; //输入字符串索引, 排序字符串长度
    fgets(str, 1000, stdin);
    // scanf("%s", str); //从标准输入读取字符串到输入字符串中
    // printf("%s", str);
    for (id = 0, len = 0; str[id]; id++) //遍历输入字符串
        if (isalpha(str[id])) //检查当前字符是否是字母
            alp[len++] = str[id]; //添加到排序字符串并更新长度
    qsort(alp, len, sizeof(char), compare); //按字母顺序排序
    for (id = 0, len = 0; str[id]; id++) //再次遍历输入字符串
        if (isalpha(str[id])) //检查当前字符是否是字母
            str[id] = alp[len++]; // 用排序字符串的字符替换它
    printf("%s", str); //将修改后的字符串打印到标准输出

    return 0;
}

全部评论

相关推荐

03-21 15:33
惠州学院 市场
点赞 评论 收藏
分享
喜欢喜欢喜欢:这是我见过最长最臭的简历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务