题解 | #字符串加解密#
字符串加解密
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;
}
}