题解 | #字符串加解密#

字符串加解密

https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a

#include <asm-generic/errno.h>
#include <cctype>
#include <iostream>
using namespace std;

void encrpyt(string &str){
    for(auto &ch : str){//注意引用符号,不然无法更改
        if(isalpha(ch)){
            if(islower(ch)){
                if(ch=='z')
                    ch = 'A';
                else
                    ch = toupper(ch+1);//返回int型值,是ASCII码,所以赋给char时,会输出对应字符
            }else{
                if(ch=='Z')
                    ch = 'a';
                else
                    ch = tolower(ch+1);//返回int型值,是ASCII码,所以赋给char时,会输出对应字符
            }   
        }else if(isdigit(ch)){
            int num = (ch-'0'+1)%10;
            ch = num+'0';
        }
    }
}

void decrpyt(string &str){
    for(auto &ch : str){
        if(isalpha(ch)){
            if(islower(ch)){
                if(ch=='a')
                    ch = 'Z';
                else
                    ch = toupper(ch-1);//返回int型值,是ASCII码,所以赋给char时,会输出对应字符
            }else{
                if(ch=='A')
                    ch = 'z';
                else
                    ch = tolower(ch-1);//返回int型值,是ASCII码,所以赋给char时,会输出对应字符
            }
        }else if(isdigit(ch)){
            if(ch=='0')
                ch = '9';
            else{
                ch = ch-1;
            }
        }
    }
}
/**
数字解密对应关系
0 9(特殊情况)
1 0 (-1)
2 1 (-1)
3 2 (-1)
……… (-1)
9 8 (-1)
*/
int main() {
    string str1,str2,str3,str4;
    getline(cin,str1);
    getline(cin,str2);
    encrpyt(str1);
    decrpyt(str2);
    cout<<str1<<endl<<str2<<endl;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务