我正在尝试制作某种加密和解密程序,它需要一个字母并将其转换为键盘上的下一个字母(如下所示)
data = data.replace('q', 'w');
data = data.replace('w', 'e');
(数据是一个字符串)
使用此代码,它会将“q”转换为“w”,但随后将相同的“w”转换为“e”,我不希望这种情况发生。我将如何避免这种情况?
This encoding method is known as Caesar cipher. Simple googling of Caesar cipher would get you lot of code snippets. For your convenience i have attached a code snippet below .
class CaesarCipher {
private final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public String encrypt(String plainText,int shiftKey)
{
plainText = plainText.toLowerCase();
String cipherText="";
for(int i=0;i<plainText.length();i++)
{
int charPosition = ALPHABET.indexOf(plainText.charAt(i));
int keyVal = (shiftKey+charPosition)%26;
char replaceVal = this.ALPHABET.charAt(keyVal);
cipherText += replaceVal;
}
return cipherText;
}
public String decrypt(String cipherText, int shiftKey)
{
cipherText = cipherText.toLowerCase();
String plainText="";
for(int i=0;i<cipherText.length();i++)
{
int charPosition = this.ALPHABET.indexOf(cipherText.charAt(i));
int keyVal = (charPosition-shiftKey)%26;
if(keyVal<0)
{
keyVal = this.ALPHABET.length() + keyVal;
}
char replaceVal = this.ALPHABET.charAt(keyVal);
plainText += replaceVal;
}
return plainText;
}
}
class CaesarDemo {
public static void main(String args[])
{
String plainText = "studentitzone";
int shiftKey=4;
CaesarCipher cc = new CaesarCipher();
String cipherText = cc.encrypt(plainText,shiftKey);
System.out.println("Your Plain Text :" + plainText);
System.out.println("Your Cipher Text :" + cipherText);
String cPlainText = cc.decrypt(cipherText,shiftKey);
System.out.println("Your Plain Text :" + cPlainText);
}
}
Where the value for shiftkey determines the number of character you need to shift. for example if shiftkey = 4 then all A will be replaced by D .
Source : http://en.wikipedia.org/wiki/Caesar_cipher
http://beta.studentitzone.com/UI/viewarticle/Caesar-cipher-Encryption-and-Decryption-Program-in-Java
Hope this helps
This will do the trick:
String data = "...";
StringBuilder finalData = new StringBuilder(data.length());
for(int i = 0; i < data.length() - 1; i++) {
char replacement = getReplacement(data.charAt(i));
finalData.append(replacement);
}
finalData.append(data.charAt(data.length() - 1));
String result = finalData.toString();
看起来您正在尝试将键盘上的键与右侧的键映射到它。您可以使用 HashMap 手动将每个键映射到特定字符。为这么多字符添加映射非常繁琐!我不知道如何动态映射它们。
public static void foo(String str) {
HashMap<Character, Character> map = new HashMap<Character, Character>();
char c;
StringBuilder sb = new StringBuilder();
map.put('q', 'w');
map.put('w', 'e');
map.put('e', 'r');
... // Add some more mappings here
...
for (int i = 0; i < str.length(); i++) {
c = str.toLowerCase().charAt(i);
sb.append(map.get(c));
}
String result = sb.toString();
System.out.println(result);
}