題目描述
編寫一個程序,將輸入字符串中的字符按如下規則排序。
規則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).
用一個vector記錄字符串中的字母,外循環用字母的順序,內循環為字符串數
1 #include<iostream> 2 #include<string> 3 #include<vector> 4 using namespace std; 5 bool isupper(char ch) 6 { 7 if ( (ch >= 'A'&&ch <= 'Z')) 8 return true; 9 else 10 return false; 11 } 12 bool islower(char ch) 13 { 14 if(ch>='a'&&ch<='z') 15 return true; 16 else 17 return false; 18 } 19 20 int main() 21 { 22 string str; 23 while (getline(cin, str)) 24 { 25 int len = str.size(); 26 vector<char>vec; 27 for(int i=0;i<26;i++) 28 { 29 for(int j=0;j<len;j++) 30 { 31 if(str[j]-'a'==i ||str[j]-'A'==i) 32 vec.push_back(str[j]); 33 } 34 } 35 for(int j=0,k=0;j<len&&k<vec.size();j++) 36 { 37 if(isupper(str[j])|| islower(str[j])) 38 str[j]=vec[k++]; 39 } 40 41 42 43 44 cout << str << endl; 45 } 46 return 0; 47 }