题解 | #字符串加解密#
字符串加解密
http://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
字符串加解密:C语言解法
对于输入一行代表解密,一行代表加密的字符串可用 mod2 进行判断加密还是解密。 方法里对每个字符单独判断并转换,最后输出字符串。
#include<stdio.h>
void encryption_and_decrypt(char *str, int flag){
int temp = 'a'-'A';
int len = strlen(str);
for(int i=0; i<len; i++){
if(str[i]>='A' && str[i]<='Z'){
if(!flag)
str[i]=str[i]+1>'Z'?'a':str[i]+temp+1;
else
str[i]=str[i]-1<'A'?'z':str[i]+temp-1;
}else if(str[i]>='a' && str[i]<='z'){
if(!flag)
str[i]=str[i]+1>'z'?'A':str[i]-temp+1;
else
str[i]=str[i]-1<'a'?'Z':str[i]-temp-1;
}else if(str[i]>='0' && str[i]<='9'){
if(!flag)
str[i]=str[i]+1>'9'?'0':str[i]+1;
else
str[i]=str[i]-1<'0'?'9':str[i]-1;
}
}
printf("%s\n",str);
}
int main(){
int flag = 0;
char str[1000] = {""};
while(gets(&str)){
encryption_and_decrypt(str, flag%2);
flag++;
}
}