题解 | #字符串加解密#

字符串加解密

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

#include<bits/stdc++.h>
using namespace std;

//加密
string& encryption(string& str){
    for(int i = 0; i < str.size(); i++){
        if(islower(str[i])){          //小写字母字符
            if(str[i] == 'z'){
                str[i] = 'A';
            }
            else{
                str[i] = toupper(str[i] + 1);
            }
        }
        else if(isupper(str[i])){     //大写字母字符
            if(str[i] == 'Z'){
                str[i] = 'a';
            }
            else{
                str[i] = tolower(str[i] + 1);
            }
        }
        else if(isdigit(str[i])){     //数字字符
            if(str[i] == '9'){
                str[i] = '0';
            }
            else{
                str[i] = str[i] + 1;
            }
        }
    }
    return str;
}


//解密
string& decryption(string& str){
    for(int i = 0; i < str.size(); i++){
        if(islower(str[i])){          //小写字母字符
            if(str[i] == 'a'){
                str[i] = 'Z';
            }
            else{
                str[i] = toupper(str[i] - 1);
            }
        }
        else if(isupper(str[i])){     //大写字母字符
            if(str[i] == 'A'){
                str[i] = 'z';
            }
            else{
                str[i] = tolower(str[i] - 1);
            }
        }
        else if(isdigit(str[i])){     //数字字符
            if(str[i] == '0'){
                str[i] = '9';
            }
            else{
                str[i] = str[i] - 1;
            }
        }
    }
    return str;
}


int main(){
    string str1; //要加密的字符串
    string str2; //要解密的字符串
    
    while(getline(cin, str1) && getline(cin, str2)){
        string res1 = encryption(str1);
        string res2 = decryption(str2);
        
        cout << res1 << endl;
        cout << res2 << endl;
    }
    
    return 0;
}
全部评论

相关推荐

一条从:又想干活还想拿工资,什么好事都让你占了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务