#字符串排序#权重标记+C语言fgets处理多行字符串

字符串排序

https://www.nowcoder.com/practice/d9aa3894d3aa4887843a85d26daa4437

/*
处理的规则如下:大小写字母按照字母序
同一个字母之间不再改变排序
其他字符保持原位 

思路如下:第一次遍历标记出其他字符,排序的时候先读其标记,标记为英文字符才能继续排序
用距离A/a的距离代表权值,用该权值进行排序

需要注意空白符也是要读入的,但是不会排序

第一遍可以标注字符的权重,把权重非-1的拿出来排序,然后用先排好序的数组对原数组中权重非-1的位置进行填空即可

另:用fgets处理多行字符串
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

typedef struct node
{
    char data;
    int weight; //权重
}node;

int cmp(const void* a,const void* b)
{
    node c = *(node*) a;
    node d = *(node*) b;
    return c.weight - d.weight; //根据权重排序
}

int main() {
    char in_str[2000]; //读取输入
    node total[2000]; //存储
    node temp[2000]; //转存并排序
    //while(scanf("%[^\n]",in_str)) //原思路 用来读入空白符
    while(fgets(in_str,sizeof(in_str),stdin) != NULL)
    {
        int len = strlen(in_str);
        for(int i=0;i<len;i++)
        {
            total[i].data = in_str[i];
            if((in_str[i]<='z'&&in_str[i]>='a')||(in_str[i]<='Z'&&in_str[i]>='A'))
            {
                if(in_str[i]<='z'&&in_str[i]>='a')
                {
                    total[i].weight = in_str[i] - 'a'; //权重标记
                }
                else
                {
                    total[i].weight = in_str[i]-'A'; //权重标记
                }
            }
            else
            {
                //其他符号 权重标记-1
                total[i].weight = -1;
            }
        }
        //权重标记结束

        //转存
        int j=0;
        for(int i=0;i<len;i++)
        {
            if(total[i].weight != -1)
            {
                temp[j].weight = total[i].weight;
                temp[j].data = total[i].data;
                j++;
            }
        }

        //排序
        qsort(temp,j,sizeof(node),cmp);

        //替换
        int temp_count;
        for(int i=0,temp_count=0;i<len&&temp_count<j;i++)
        {
            if(total[i].weight != -1)
            {
                total[i].data = temp[temp_count].data;
                temp_count++;
            }
        }

        //输出
        for(int i=0;i<len;i++)
        {
            printf("%c",total[i].data);
        }
        //printf("\n");
        //getchar(); //对应scanf,吃掉一个换行符
    }
    return 0;
}

想问问各位大佬,while(scanf("%[^\n]",in_str))+getchar()(吃一个换行符),最后导致最后一行字符串退不出循环了,有解决思路吗

全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务