1.题目描述
输入一串字符,包含数字[0-9]和小写字母[a-z],要求按数字从小到大、字母从a到z排序,并且所有数字排在字母后面
- 输入示例:
a31bz
- 输出示例:
abz13
2.题目解析
-
预备知识
sort(first,last)
以升序排序范围
[first, last)
中的元素。sort(first,last,cmp)
cmp(a,b)
比较函数,a
与b
不交换返回true
(也就是想要的顺序);first
与last
交换返回false
。 解题思路:
字符排序,判断条件追加字母与数字的区分(字母的ascii码比数字小)。
3.参考答案
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
cin >> s;
sort(s.begin(),s.end());
int pos = 0;
for(int i=0;i<s.size();++i){
if(!('0'<=s[i] && s[i] <= '9')){
pos = i;
break;
}
}
// 截取数字部分
string num = s.substr(0,pos);
// 截取字母部分
string str = s.substr(pos);
cout << str+num;
return 0;
}
- 使用STL函数
sort()
#include <bits/stdc++.h>
using namespace std;
bool cmp(int a,int b){
// a 和 b一个是数字一个是字母
// '0' <= a && a <='9'
// 'a' <= b && b <='z'
if(isdigit(a) && isalpha(b)){
return false;
}
if(isdigit(b) && isalpha(a)){
return true;
}
// a 和 b都是数字或都是字母
return a < b;// 正确的顺序
}
int main() {
string s;
cin >> s;
sort(s.begin(),s.end(),cmp);
cout << s;
return 0;
}
使用冒泡排序
#include <bits/stdc++.h>
using namespace std;
int main(){
string str;
cin >> str;
for(int i=0;i!=str.size();++i){
for(int j=0;j!=str.size()-(i+1);j++){
if((str[j] <= '9' && str[j+1] >= 'a') ||
(str[j] > str[j+1] && str[j] <= '9') ||
(str[j] > str[j+1] && str[j+1] >= 'a')){
swap(str[j],str[j+1]);
}
}
}
cout << str << "\n";
}