题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s1 = in.nextLine(); String s2 = in.nextLine(); System.out.println(encrypt(s1)); System.out.println(decrypt(s2)); } // 加密 public static String encrypt(String str) { char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { if (Character.isUpperCase(ch[i])) { ch[i] = (char) ('a' + ((Character.toLowerCase(ch[i]) - 'a' + 1) % 26)); } else if (Character.isLowerCase(ch[i])) { ch[i] = (char) ('A' + ((Character.toUpperCase(ch[i]) - 'A' + 1) % 26)); } else if (Character.isDigit(ch[i])) { if (ch[i] == '9') { ch[i] = '0'; } else { ch[i] = (char) (ch[i] + 1); } } } return String.valueOf(ch); } // 解密 public static String decrypt(String str) { char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { if (Character.isUpperCase(ch[i])) { ch[i] = (char) ('a' + ((Character.toLowerCase(ch[i]) - 'a' - 1 + 26) % 26)); } else if (Character.isLowerCase(ch[i])) { ch[i] = (char) ('A' + ((Character.toUpperCase(ch[i]) - 'A' - 1 + 26) % 26)); } else if (Character.isDigit(ch[i])) { if (ch[i] == '0') { ch[i] = '9'; } else { ch[i] = (char) (ch[i] - 1); } } } return String.valueOf(ch); } }