言語処理100本ノック 第1章: 準備運動 08
08. 暗号文
与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.
- 英小文字ならば(219 - 文字コード)の文字に置換
- その他の文字はそのまま出力
この関数を用い,英語のメッセージを暗号化・復号化せよ.
java
package net.vg4; import java.util.ArrayList; import java.util.List; public class Main { public static String cipher(String str) { List<String> ret = new ArrayList<>(); for (String s : str.split("")) { if (s.matches("[a-z]")) { try { byte[] ba = s.getBytes("US-ASCII"); ba[0] = (byte) (219 - ba[0]); ret.add(new String(ba, "US-ASCII")); } catch (Exception e) { ; } } else { ret.add(s); } } return String.join("", ret); } public static void main(String[] args) { String sample = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."; String encoded = cipher(sample); System.out.println(encoded); String decoded = cipher(encoded); System.out.println(decoded); } }