题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str1=in.nextLine();//待加密字符串 String str2=in.nextLine();//待解密字符串 System.out.println(encode(str1)); System.out.println(decode(str2)); } //加密函数 public static String encode(String code){ StringBuffer res=new StringBuffer(); char[] codeChar=code.toCharArray(); //加密 for(int i=0;i<codeChar.length;i++){ char tempCh='a'; if (Character.isLetter(codeChar[i])) {//函数判断是字母 另有按照数字、按照字母范围判断 tempCh=setCharacter(codeChar[i]); } if (Character.isDigit(codeChar[i])) {//函数判断是数字 另有按照数字、按照数字范围判断 tempCh=setDigital(codeChar[i]); } res.append(tempCh); } return res.toString(); } //解密函数 public static String decode(String code){ StringBuffer res=new StringBuffer(); char[] codeChar = code.toCharArray(); for(int i=0;i<codeChar.length;i++){ char tempCh='a'; if (Character.isLetter(codeChar[i])) { tempCh=getCharacter(codeChar[i]); } if (Character.isDigit(codeChar[i])) { tempCh=getDigital(codeChar[i]); } res.append(tempCh); } return res.toString(); } //加密数字 public static char setDigital(char num){ char res=(char)((num-'0'+1)%10+'0'); return res; } //加密字母 public static char setCharacter(char charc){ char res='a'; if(charc<'a'){ if(charc!='Z'){ res=(char)(charc-'A'+'a'+1); }else{ res='a'; } }else{ if(charc!='z'){ res=(char)(charc-'a'+'A'+1); }else{ res='A'; } } return res; } //解密数字 public static char getDigital(char num){ char res=(char)((num-'0'+9)%10+'0'); return res; } //解密字母 public static char getCharacter(char charc){ char res='a'; if(charc<'a'){ if(charc!='A'){ res=(char)(charc-'A'+'a'-1); }else{ res='z'; } }else{ if(charc!='a'){ res=(char)(charc-'a'+'A'-1); }else{ res='Z'; } } return res; } }