题解 | #字符串加解密#

字符串加解密

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

写个解密和加密的函数,字符进行+1或-1就好了

#include <string>
#include <map>
#include <vector>

using namespace std;
string encryption(string str){
    for(int i = 0;i<str.size();i++){
        if(isalpha(str[i])){
            if(str[i]>='a'&&str[i]<'z'){
                str[i]+=1;
                str[i]=toupper(str[i]);
            }
            else if(str[i]>='A'&&str[i]<'Z'){
                str[i]+=1;
                str[i]=tolower(str[i]);
            }
            else if(str[i]=='z')str[i]='A';
            else str[i]='a';
        }//if is alpha
        else if (isdigit(str[i])){
            if(str[i]>='0'&&str[i]<'9')str[i]=str[i]+1;
            else if(str[i]=='9')str[i]=str[i]-9;
            
        }//else if is digit
        
    }//for
    return str;
}
string decryption(string str){
      for(int i = 0;i<str.size();i++){
        if(isalpha(str[i])){
            if(str[i]>'a'&&str[i]<='z'){
                str[i]-=1;
                str[i]=toupper(str[i]);
            }
            else if(str[i]>'A'&&str[i]<='Z'){
                str[i]-=1;
                str[i]=tolower(str[i]);
            }
            else if(str[i]=='a')str[i]='Z';
            else str[i]='z';
        }//if is alpha
        else if (isdigit(str[i])){
            if(str[i]>'0'&&str[i]<='9')str[i]=str[i]-1;
            else if(str[i]=='0')str[i]=str[i]+9;
            
        }//else if is digit
        
    }//for
    return str;
}

int main() {
    string str;
    bool first = true;
    while(cin>>str){
        string out;
        if(first)    {out=encryption(str);first=!first;}
        else    {out=decryption(str);first=!first;}
        
        cout<<out<<endl;
    }
    
    
    
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-27 15:19
简历上能写3个月吗?
码农索隆:大胆写,主要你能把实习经历包装好,可以看一下我这篇帖子https://www.nowcoder.com/share/jump/4888395581180798063
点赞 评论 收藏
分享
真烦好烦真烦:牛友太有实力了
点赞 评论 收藏
分享
06-27 18:45
中山大学 Ruby
25届应届毕业生,来广州2个礼拜了,找不到工作,绝望了,太难过了…
应届想染班味:9爷找不到工作只能说明,太摆了或者太挑了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务