题解 | #字符串合并处理#
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
#include <iostream>
#include <string>
#include <bitset>
#include <cctype>//toupper()
#include <algorithm>//sort()和reverse()
using namespace std;
//核心代码,处理字符串转换
string& transform(string &str)
{
string hexdic = "0123456789ABCDEF";//十六进制字典
string binstr;//存储二进制字符串
int value;//存储整数
for (char &x : str)
{
if ((x >= '0' && x <= '9') || (x >= 'A' && x <= 'F') || (x >= 'a' && x <= 'f'))
{
if ( x >= '0' && x <= '9')//将字符转换成整数
{
value = x - '0';
}
else
{
value = toupper(x) - 'A' + 10;
}
//将整数转换成4位二进制字符串
binstr = bitset<4>(value).to_string();
//倒序
reverse(binstr.begin(),binstr.end());
//二进制字符串转换成整数
value = stoi(binstr, nullptr, 2);
//将x修改为对应索引的字符
x = hexdic.at(value);
}
}
return str;
}
int main() {
//首先处理输入
string str, str1, str2;
cin >> str1;
cin >> str2;
//第一步,合并字符串
str = str1 + str2;
//第二步,对奇偶位字符分别排序
str1.clear();//str1放奇数位字符
str2.clear();//str2放偶数位字符
for (int i = 0; i < str.size(); ++i)
{
if (i % 2 == 1)
{
str1 += str[i];
}
else
{
str2 += str[i];
}
}
//进行字典序排序
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
//按偶奇顺序放入合并串
for (int i = 0; i < str.size(); ++i)
{
if (i % 2 == 0)
{
str[i] = str2[i / 2];
}
else
{
str[i] = str1[i / 2];
}
}
//第三步,对合并字符串进行转换并输出
cout << transform(str) << endl;
return 0;
}
比前几个密码题处理流程更复杂了

