HJ29 字符串加解密

描述

对输入的字符串进行加解密,并输出。

加密方法为:

当内容是英文字母时则用该英文字母的后一个字母替换,同时字母变换大小写,如字母a时则替换为B;字母Z时则替换为a;

当内容是数字时则把该数字加1,如0替换1,1替换2,9替换0;

其他字符不做变化。

解密方法为加密的逆过程。

数据范围:输入的两个字符串长度满足 1 \le n \le 1000 \1≤n≤1000 ,保证输入的字符串都是只由大小写字母或者数字组成

输入描述:

第一行输入一串要加密的密码
第二行输入一串加过密的密码

输出描述:

第一行输出加密后的字符
第二行输出解密后的字符

示例1

输入:

abcdefg
BCDEFGH

复制输出:

BCDEFGH
abcdefg

#include <iostream>
#include <string.h>
/*对字符串进行加密      abcdefg
    加密时候如果是大写字母则大写变小写加1
           如果是小写字母则小写变大写加1
*/
std::string encrypt(std::string encryptStr)
{
    std::string rtnStr = "";
    for(int i = 0; i < encryptStr.length(); ++i)
    {
        char c = encryptStr[i];
        if(std::isupper(c))                 //是大写字母
        {
            if(c != 'Z')
            {
                rtnStr += (char)(c + 33);
            }
            else
            {
                rtnStr += 'a';
            }
        }
        else if(std::islower(c))            //是小写字母
        {
            if(c != 'z')
            {
                rtnStr += (char)(c - 31);
            }
            else
            {
                rtnStr += 'A';
            }
        }
        else if(std::isdigit(c))            //是数字
        {
            if(c != '9')
            {
                rtnStr += (char)(c + 1);
            }
            else
            {
                rtnStr += '0';
            }
        }
    }

    return rtnStr;
}

/*对字符串进行解密
    如果是大写字母则变小写减1
    如果是小写字母则变大写加1
*/
std::string decrypt(std::string encryptStr)
{
    std::string rtnStr = "";
    for(int i = 0; i < encryptStr.length(); ++i)
    {
        char c = encryptStr[i];
        if(std::isupper(c))                 //是大写字母
        {
            if(c != 'A')
            {
                rtnStr += (char)(c + 31);
            }
            else
            {
                rtnStr += 'z';
            }
        }
        else if(std::islower(c))            //是小写字母
        {
            if(c != 'a')
            {
                rtnStr += (char)(c - 33);
            }
            else
            {
                rtnStr += 'Z';
            }
        }
        else if(std::isdigit(c))            //是数字
        {
            if(c != '0')
            {
                rtnStr += (char)(c - 1);
            }
            else
            {
                rtnStr += '9';
            }
        }
    }

    return rtnStr;
}

int main()
{
    std::string encryptStr;             //ABCDEFGHIJKLMNOPQRSTUVWXYZ    abcdefghijklmnopqrstuvwxyz  0123456789
    getline(std::cin, encryptStr);

    std::string decryptStr;
    getline(std::cin, decryptStr);

    std::cout << encrypt(encryptStr) << std::endl;
    std::cout << decrypt(decryptStr) << std::endl;


    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值