题目
描述
编写一个程序,将输入字符串中的字符按如下规则排序。
规则1:英文字母从A到Z排列,不区分大小写。
如,输入:Type 输出:epTy
规则2:同一个英文字母的大小写同时存在时,按照输入顺序排列。
如,输入:BabA 输出:aABb
规则3:非英文字母的其它字符保持原来的位置。
如,输入:By?e 输出:Be?y
样例输入
A Famous Saying: Much Ado About Nothing (2012/8).
样例输出
A aaAAbc dFgghh: iimM nNn oooos Sttuuuy (2012/8).
思路
- 排序
- 找出不变的位置
代码
#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
int main()
{
string str;
getline(cin,str);
int n=str.size();
int i,j,temp;
//找最小的字母
for (i=1; i<=n-1; i++)
{
for (j=n-1; j>=i; j--)
{
int k=j;
if (isalpha(str[j]))
{
//跳过去非字符串
while(!isalpha(str[k-1]))
{
k--;
}
if (tolower(str[j])<tolower(str[k-1]))
{
temp=str[j];
str[j]=str[k-1];
str[k-1]=temp;
}
}
else
{
continue;
}
}
}
cout<<str<<endl;
}
代码2
#include <iostream>
#include <string>
#include <ctype.h>
#include <algorithm>
using namespace std;
int compareAlpha(const char &ch1,const char &ch2)
{
return tolower(ch1)<tolower(ch2);
}
int main()
{
string str,temp;
getline(cin,str);
temp=str;
int n=str.size();
int pos=0;
//排序(不区分字母大小写)
sort(temp.begin(),temp.end(),compareAlpha);
cout<<temp<<endl;
//找到非字母的位置
while(!isalpha(temp[pos]))
{
++pos;
}
//将排序后的字母对原字符串进行替换即可
for(int i=0; i<n; ++i)
{
if(isalpha(str[i]))
{
str[i]=temp[pos];
pos++;
}
else
{
continue;
}
}
//输出
cout<<str<<endl;
}