题解 | #字符串合并处理#C++使用Map容器来转换字符
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
#include <string> #include <iostream> #include <algorithm> #include <cctype> #include <map> using namespace std; int main() { map<char, char> p = { {'0','0'},{'1','8'},{'2','4'},{'3','C'},{'4','2'},{'5','A'},{'6','6'},{'7','E'} ,{'8','1'},{'9','9'},{'a','5'},{'b','D'},{'c','3'},{'d','B'},{'e','7'},{'f','F'} }; //用于转换字符 string str1, str2; while (cin >> str1 >> str2) { string temp = str1 + str2; //合并 str1.clear(); //分别存储偶数位与奇数位字符 str2.clear(); for (int i = 0; i < temp.size(); i++) { if (i % 2 == 0) { str1 += temp[i]; } else { str2 += temp[i]; } } sort(str1.begin(), str1.end()); //存储完直接调用sort函数,自动按ASCⅡ码排升序 sort(str2.begin(), str2.end()); for (int i = 0; i < str1.size(); i++) { if (p.find(tolower(str1[i])) != p.end()) //tolower函数用来将大写字母转化为小写,因为map容器中只列了小写字母的转换关系, //find函数用来查找是否存在转换关系的原字符 str1[i] = p[tolower(str1[i])]; //使用map容器转换 } for (int i = 0; i < str2.size(); i++) { if (p.find(tolower(str2[i])) != p.end()) str2[i] = p[tolower(str2[i])]; //同上理 } int x = 0, y = 0; for (int i = 0; i < temp.size(); i++) { if (i % 2 == 0) { cout<<str1[x++]; //按原有奇偶顺序来输出 } else { cout<<str2[y++]; } } } return 0; }