字符串加解密

題目描述

一、對輸入的字符串進行加解密,並輸出。

2加密方法爲:
當內容是英文字母時則用該英文字母的後一個字母替換,同時字母變換大小寫,如字母a時則替換爲B;字母Z時則替換爲a;
當內容是數字時則把該數字加1,如0替換1,1替換2,9替換0;
其餘字符不作變化。

三、解密方法爲加密的逆過程。

接口描述:實現接口,每一個接口實現1個基本操做:

    void encrypt (char aucPassword[], char aucResult[]):在該函數中實現字符串加密並輸出
說明:
    一、字符串以\0結尾。
    二、字符串最長100個字符。

    int unEncrypt (char result[], char password[]):在該函數中實現字符串解密並輸出
說明:
    一、字符串以\0結尾。
    二、字符串最長100個字符。

輸入描述

輸入說明
輸入一串要加密的密碼
輸入一串加過密的密碼

輸出描述

輸出說明
輸出加密後的字符
輸出解密後的字符

輸入例子

abcdefg
BCDEFGH

輸出例子

BCDEFGH
abcdefg

算法實現

import java.util.Scanner;

/**
 * All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            String input = scanner.nextLine();
            System.out.println(encrypt(input));
            input = scanner.nextLine();
            System.out.println(unencrypt(input));
        }

        scanner.close();
    }

    /**
     * 字符串解密
     *
     * @param s
     * @return
     */
    private static String unencrypt(String s) {
        char[][] mask = {
                {'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y'},
                {'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y'},
                {'9', '0', '1', '2', '3', '4', '5', '6', '7', '8'}
        };
        return convert(s, mask);
    }

    /**
     * 字符串加密
     *
     * @param s
     * @return
     */
    private static String encrypt(String s) {
        char[][] mask = {
                {'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a'},
                {'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'A'},
                {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}
        };

        return convert(s, mask);
    }

    /**
     * 根據掩碼錶對字符串進行轉換
     *
     * @param s
     * @param mask
     * @return
     */
    private static String convert(String s, char[][] mask) {
        StringBuilder builder = new StringBuilder(s.length());
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 'A' && c <= 'Z') {
                builder.append(mask[0][c - 'A']);
            } else if (c >= 'a' && c <= 'z') {
                builder.append(mask[1][c - 'a']);
            } else {
                builder.append(mask[2][c - '0']);
            }
        }
        return builder.toString();
    }
}
相關文章
相關標籤/搜索