严正声明:本文系作者davidhopper原创,未经许可,不得转载。
题目描述
-
对输入的字符串进行加解密,并输出。
-
加密方法为:
当内容是英文字母时则用该英文字母的后一个字母替换,同时字母变换大小写,如字母a时则替换为B;字母Z时则替换为a;
当内容是数字时则把该数字加1,如0替换1,1替换2,9替换0;
其他字符不做变化。 -
解密方法为加密的逆过程。
说明
- 字符串以\0结尾。
- 字符串最长100个字符。
输入描述
输入一串要加密的密码
输入一串加过密的密码
输出描述
输出加密后的字符
输出解密后的字符
示例1
输入
abcdefg
BCDEFGH
输出
BCDEFGH
abcdefg
答案
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <string>
const std::string A_TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const std::string D_TABLE = "0123456789";
void Encrypt(const std::string& contents, std::string& passwords);
void Decrypt(const std::string& passwords, std::string& contents);
int main() {
std::string in_contents, out_contents, in_passwords, out_passwords;
while (std::getline(std::cin, in_contents)) {
std::getline(std::cin, in_passwords);
Encrypt(in_contents, out_passwords);
Decrypt(in_passwords, out_contents);
std::cout << out_passwords << std::endl;
std::cout << out_contents << std::endl;
}
return 0;
}
void Encrypt(const std::string& contents, std::string& passwords) {
if (contents.empty()) {
return;
}
passwords = contents;
char content = '0';
char password = '0';
for (std::size_t i = 0; i < contents.size(); ++i) {
content = contents[i];
password = content;
if (std::isalpha(content)) {
auto pos = A_TABLE.find(std::toupper(content));
if (std::string::npos != pos) {
password = pos < (A_TABLE.size() - 1) ? A_TABLE[pos + 1] : A_TABLE[0];
if (std::isupper(content)) {
password = std::tolower(password);
}
}
} else if (std::isdigit(content)) {
auto pos = D_TABLE.find(content);
if (std::string::npos != pos) {
password = pos < (D_TABLE.size() - 1) ? D_TABLE[pos + 1] : D_TABLE[0];
}
} else {
continue;
}
passwords[i] = password;
}
}
void Decrypt(const std::string& passwords, std::string& contents) {
if (passwords.empty()) {
return;
}
contents = passwords;
char content = '0';
char password = '0';
for (std::size_t i = 0; i < passwords.size(); ++i) {
password = passwords[i];
content = password;
if (std::isalpha(password)) {
auto pos = A_TABLE.find(std::toupper(password));
if (std::string::npos != pos) {
content = pos > 0 ? A_TABLE[pos - 1] : A_TABLE[A_TABLE.size() - 1];
if (std::isupper(password)) {
content = std::tolower(content);
}
}
} else if (std::isdigit(password)) {
auto pos = D_TABLE.find(password);
if (std::string::npos != pos) {
content = pos > 0 ? D_TABLE[pos - 1] : D_TABLE[D_TABLE.size() - 1];
}
} else {
continue;
}
contents[i] = content;
}
}
说明
在线测试系统的输入检测很弱智,一定要使用类似于while (std::getline(std::cin, line))
的循环来检查输入数据,否则总是无法通过用例测试。