通過異或運算符號與一個指定的值進行異或運算,從而改變字符串每個字符的值,這樣就可以得到加密后的字符串。
import java.util.Scanner; public class Encypt { public static void main(String args[]){ Scanner scan = new Scanner(System.in); System.out.println("請輸入一個英文字符串或解密字符串:"); String password = scan.nextLine(); //獲取用戶輸入 char[] array = password.toCharArray(); //獲取字符數組 for(int i=0;i<array.length;i++) //遍歷字符數組 { array[i]=(char)(array[i]^20000); //對每個數組元素進行異或運算 } System.out.println("加密或解密結果如下:"); System.out.println(new String(array)); } }
輸出結果: