编写一个程序,将输入字符串中的字符按如下规则排序。
规则 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).
示例1
题目地址:
思路一:将输入字符串中每一位字母加入vector,然后用stable_sort进行稳定排序,最后按顺序覆盖原字符串中的字母
#include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; bool charcompare(char a, char b) { a = toupper(a); b = toupper(b); return a < b; } int main() { string str = ""; while (getline(cin, str)) { vector<char> charVector; for (char c : str) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { charVector.push_back(c); } } stable_sort(charVector.begin(), charVector.end(), charcompare); int count = 0; for (char &c : str) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { c = charVector[count]; count++; } } cout << str << endl; } return 0; }思路二:不排序,网友解法
链接:https://www.nowcoder.com/questionTerminal/5190a1db6f4f4ddb92fd9c365c944584 来源:牛客网 #include<vector> #include<iostream> #include<string> using namespace std; int main() { string s; vector<char> tempChar; while(getline(cin,s)) { tempChar.clear(); int len = s.size(); for(int j=0; j<26; j++) { for(int i=0; i<len; i++) { if(s[i]-'a'==j||s[i]-'A'==j) { tempChar.push_back(s[i]); } } } for(int i=0,k=0;(i<len)&&k<tempChar.size();i++) { if((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z')) s[i]=tempChar[k++]; } cout<<s<<endl; } return 0; }