描述
对输入的字符串进行加解密,并输出。
加密方法为:
当内容是英文字母时则用该英文字母的后一个字母替换,同时字母变换大小写,如字母a时则替换为B;字母Z时则替换为a;
当内容是数字时则把该数字加1,如0替换1,1替换2,9替换0;
其他字符不做变化。
解密方法为加密的逆过程。
数据范围: 输入的两个字符串长度满足 1000 \1≤n≤1000 ,保证输入的字符串都是只由大小写字母或者数字组成
输入描述:
第一行输入一串要加密的密码
第二行输入一串加过密的密码
输出描述:
第一行输出加密后的字符
第二行输出解密后的字符
示例1
输入:
abcdefg
BCDEFGH
输出:
BCDEFGH
abcdefg
实现
#include <stdio.h>
#include <string.h>
typedef enum _CType {
CTYPE_UPER = 0,
CTYPE_LOWER,
CTYPE_NUMBER,
CTYPE_OTHER,
} CType;
void fmtBuf(char *buf)
{
int len = strlen(buf);
for (int i = 0; i < len; i++) {
if ((buf[i] == '\r') || (buf[i] == '\n')) {
buf[i] = '\0';
}
}
}
CType GetCharType(char c)
{
CType type;
if ((c >= 'A') && (c <= 'Z')) {
type = CTYPE_UPER;
} else if ((c >= 'a') && (c <= 'z')) {
type = CTYPE_LOWER;
} else if ((c >= '0') && (c <= '9')) {
type = CTYPE_NUMBER;
} else {
type = CTYPE_OTHER;
}
return type;
}
void encryptBuf(char *inbuf, char *outBuf)
{
int len = strlen(inbuf);
for (int i = 0; i < len; i++) {
if (GetCharType(inbuf[i]) == CTYPE_UPER) {
if (inbuf[i] == 'Z') {
outBuf[i] = 'a';
} else {
outBuf[i] = (inbuf[i] + 1) - 'A' + 'a';
}
} else if (GetCharType(inbuf[i]) == CTYPE_LOWER) {
if (inbuf[i] == 'z') {
outBuf[i] = 'A';
} else {
outBuf[i] = (inbuf[i] + 1) - 'a' + 'A';
}
} else if (GetCharType(inbuf[i]) == CTYPE_NUMBER) {
if (inbuf[i] == '9') {
outBuf[i] = '0';
} else {
outBuf[i] = inbuf[i] + 1;
}
} else {
outBuf[i] = inbuf[i];
}
}
}
void decryptBuf(char *inbuf, char *outBuf)
{
int len = strlen(inbuf);
for (int i = 0; i < len; i++) {
if (GetCharType(inbuf[i]) == CTYPE_UPER) {
if (inbuf[i] == 'A') {
outBuf[i] = 'z';
} else {
outBuf[i] = (inbuf[i] - 1) - 'A' + 'a';
}
} else if (GetCharType(inbuf[i]) == CTYPE_LOWER) {
if (inbuf[i] == 'a') {
outBuf[i] = 'Z';
} else {
outBuf[i] = (inbuf[i] - 1) - 'a' + 'A';
}
} else if (GetCharType(inbuf[i]) == CTYPE_NUMBER) {
if (inbuf[i] == '0') {
outBuf[i] = '9';
} else {
outBuf[i] = inbuf[i] - 1;
}
} else {
outBuf[i] = inbuf[i];
}
}
}
int main()
{
char inBuf[1001] = {0};
char outBuf[1001] = {0};
for (int i = 0; i < 2; i++) {
fgets(inBuf, sizeof(inBuf), stdin);
fmtBuf(inBuf);
// printf("inBuf: %s\n", inBuf);
if (i == 0) {
encryptBuf(inBuf, outBuf);
} else {
decryptBuf(inBuf, outBuf);
}
printf("%s\n", outBuf);
memset(inBuf, 0x00, sizeof(inBuf));
memset(outBuf, 0x00, sizeof(outBuf));
}
return 0;
}