Talk is cheap, show me the code.
一、问题描述
按照指定规则对输入的字符串进行处理。
详细描述:
将输入的两个字符串合并。
对合并后的字符串进行排序,要求为:下标为奇数的字符和下标为偶数的字符分别从小到大排序。这里的下标意思是字符在字符串中的位置。
对排序后的字符串进行操作,如果字符为‘0’——‘9’或者‘A’——‘F’或者‘a’——‘f’,则对他们所代表的16进制的数进行BIT倒序的操作,并转换为相应的大写字符。如字符为‘4’,为0100b,则翻转后为0010b,也就是2。转换后的字符为‘2’; 如字符为‘7’,为0111b,则翻转后为1110b,也就是e。转换后的字符为大写‘E’。
举例:输入str1为”dec”,str2为”fab”,合并为“decfab”,分别对“dca”和“efb”进行排序,排序后为“abcedf”,转换后为“5D37BF”
接口设计及说明:
/*
功能:字符串处理
输入:两个字符串,需要异常处理
输出:合并处理后的字符串,具体要求参考文档
返回:无
*/
void ProcessString(char* str1,char str2,char strOutput)
{
}
输入描述:
输入两个字符串
输出描述:
输出转化后的结果
输入例子:
dec fab
输出例子:
5D37BF
二、问题分析
这个题目纯粹地处理字符串,不过比较综合,字符串的常用变换方法都涉及到了,如果每一步都采用原始的方式将会很麻烦,采用查表法实现位反转是最好的方式。
#include <iostream>
#include <string>
#include <map>
#include <iterator>
#include <algorithm>
using namespace std;
string processString(string str1, string str2)
{
map<char, char> ma;
ma['0'] = '0';
ma['1'] = '8';
ma['2'] = '4';
ma['3'] = 'C';
ma['4'] = '2';
ma['5'] = 'A';
ma['6'] = '6';
ma['7'] = 'E';
ma['8'] = '1';
ma['9'] = '9';
ma['a'] = '5';
ma['b'] = 'D';
ma['c'] = '3';
ma['d'] = 'B';
ma['e'] = '7';
ma['f'] = 'F';
string s;
s = str1 + str2;
string s1, s2;
for (int i = 0; i < s.size(); i++)
{
if (i % 2 == 0)
{
s2 += s[i];
} else {
s1 += s[i];
}
}
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
s.clear();
int p = 0;
while (p < s1.size())
{
s = s + s2[p] + s1[p];
p++;
}
if (p < s2.size())
s += s2[p];
for (int i = 0; i < s.size(); i++)
{
if (s[i] >= '0' && s[i] <= '9' || (s[i] >= 'a' && s[i] <= 'f'))
{
s[i] = ma[s[i]];
} else if (s[i] >= 'A' && s[i] <= 'F') {
s[i] = ma[s[i] + 32];
}
}
return s;
}
int main()
{
string s1, s2;
while (cin >> s1 >> s2)
{
string s = processString(s1, s2);
cout << s << endl;
}
return 0;
}