题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s1 = sc.nextLine(); String s2 = sc.nextLine(); System.out.println(encode(s1)); System.out.println(decode(s2)); } private static String encode(String str) { StringBuilder sb = new StringBuilder(); for(int i=0; i<str.length(); i++){ char c = str.charAt(i); if(c>='0' && c<='8') sb.append( (char)(c+1) ); else if(c == '9') sb.append('0'); else if(c == 'z') sb.append('A'); else if(c == 'Z') sb.append('a'); else if(c>='a' && c<='y') sb.append( (char)(toUpperCase(c)+1) ); else if(c>='A' && c<='Y') sb.append( (char)(toLowerCase(c)+1) ); else sb.append(c); } return sb.toString(); } private static String decode(String str) { StringBuilder sb = new StringBuilder(); for(int i=0; i<str.length(); i++){ char c = str.charAt(i); if(c>='1' && c<='9') sb.append( (char)(c-1) ); else if(c == '0') sb.append('9'); else if(c == 'a') sb.append('Z'); else if(c == 'A') sb.append('z'); else if(c>='b' && c<='z') sb.append( (char)(toUpperCase(c)-1) ); else if(c>='B' && c<='Z') sb.append( (char)(toLowerCase(c)-1) ); else sb.append(c); } return sb.toString(); } public static char toUpperCase(char c1) { int a = (int) c1;//将接收到的小写字符c1转换成int类型的数据给a int b = a - 32; //a-32得出小写对应大写的ascll数值 char bb = (char)b;//最后将b转换成char类型字符给bb return bb; //返回bb;就是返回大写的字符 } public static char toLowerCase(char c1) { int a = (int) c1;//将接收到的小写字符c1转换成int类型的数据给a int b = a + 32; //a+32得出大写写对应小写的ascll数值 char bb = (char)b;//最后将b转换成char类型字符给bb return bb; //返回bb;就是返回字母小写的字符 } }