首页 > 解决方案 > 如何对字母表添加值进行简单的加密?

问题描述

标签: javamethodsunicodecharrange

解决方案


Well if it's just A-Z that you care about, you can write a simple encryption function like so:

char encrypt(char letter){
    char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    char next_letter = alphabet[(letter - 'A' + 1) % 26];
    return next_letter;
}

letter - 'A' gives us the position of the letter in the alphabet array, for example if we wanted to get the position of 'C', 'C' - 'A' = 2 and the position of alphabet[2] is indeed 'C'.

To get the next letter, we offset by 1, ie letter - 'A' + 1

The % 26 helps ensure we loop back to the beginning if we're at the end, ie when we're trying to encrypt 'Z' for example,
'Z' - 'A' + 1 = 26
26 % 26 = 0.

System.out.println(encrypt('Z'));
>>> A

Likewise, you could write a decrypt function like so:

char decrypt(char letter){
    char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    char prev_letter = alphabet[26 - (letter - 'A' + 1)];
    return prev_letter;
}

推荐阅读