字符串排序

来源:互联网 发布:苹果乐器软件 编辑:程序博客网 时间:2024/06/01 10:16

题目描述

编写一个程序,将输入字符串中的字符按如下规则排序。

规则1:英文字母从AZ排列,不区分大小写。

      如,输入:Type 输出:epTy

规则2:同一个英文字母的大小写同时存在时,按照输入顺序排列。

    如,输入:BabA 输出:aABb

规则3:非英文字母的其它字符保持原来的位置。

    如,输入:By?e 输出:Be?y

样例:

    输入:

   A Famous Saying: Much Ado About Nothing(2012/8).

    输出:

   A aaAAbc dFgghhiimM nNn oooos Sttuuuy (2012/8).



输入描述:



输出描述:


输入例子:
A Famous Saying: Much Ado About Nothing (2012/8).

输出例子:
A aaAAbc dFgghh: iimM nNn oooos Sttuuuy (2012/8).


题目思路:

受教于一位大神

先把字符的挑出来,保存进pair中,first键值保存字符,second保存位置。
挑出来之后sort排序,里面用了lambda表达式,如果转换小写之后相同,按照位置从小到大排,不相同统一按照小写字符a~z排序。
然后排序完成之后的arr重新放入原来的字符串,保证了非字母字符的位置不变。最后输出

代码:

#include<bits/stdc++.h>using namespace std;const int MAXN=1005;pair<char,int>ans[MAXN];bool cmp(pair<char,int>a,pair<char,int>b){    if(tolower(a.first)==tolower(b.first))        return a.second<b.second;    else        return tolower(a.first)<tolower(b.first);}int main(){    string s;    while(getline(cin,s))    {        int len=s.length();        int index=0;        for(int i=0;i<len;i++)        {            if(isalpha(s[i]))            {                ans[index++]=make_pair(s[i],i);            }        }        sort(ans,ans+index,cmp);        index=0;        for(int i=0;i<len;i++)        {            if(isalpha(s[i]))            {                s[i]=ans[index++].first;            }        }        cout<<s<<endl;    }    return 0;}

还有lambda表达式形式的cmp

sort(ans,ans+index,[](pair<char,int>a,pair<char,int>b)->bool{             if(tolower(a.first)==tolower(b.first))                return a.second<b.second;             return tolower(a.first)<tolower(b.first);             });


1 0