Java中的Caesar Cipher(西班牙语字符)

时间:2010-06-14 12:33:00

标签: java special-characters encryption

我正在阅读this question,我想知道是否有办法考虑整个角色范围?例如,“á”,“é”,“ö”,“ñ”,而不考虑“”([空间])? (例如,我的String是“Hello World”,标准结果是“Khoor#Zruog”;我想删除“#”,因此结果将是“KhoorZruog”)

我确定我的答案就在这段代码中:

if (c >= 32 && c <= 127)
        {
            // Change base to make life easier, and use an
            // int explicitly to avoid worrying... cast later
            int x = c - 32;
            x = (x + shift) % 96;
            chars[i] = (char) (x + 32);
        }

但是我尝试了一些东西,但它没有用。

3 个答案:

答案 0 :(得分:1)

请参阅此伪代码 - 应该可以轻松实现:

// you need to define your own range, obviously - it's not at all obvious whether
// e.g. "ź" should be included and that it should come after "z"
array char_range = ['a','á','b','c','č', (...), 'z','ź','ž'] 
// the text to encode
string plaintext = 'some text here'
// this will contain encoded text
stringbuilder ciphertext = ''
// the classic Caesar Cipher shifts by 3 chars to the right
// to decipher, reverse the sign
int shift_by = 3 
// note: character != byte, esp. not in UTF-8 (1 char could be 1 or more bytes)
for each character in plaintext
    get character_position of character in char_range // e.g. "a" would return 0
    if not in char_range // e.g. spaces and other non-letters
        do nothing // drop character 
        // alternately, you can append it to ciphertext unmodified
        continue with next character
    add shift_by to character_position
    if character_position > char_range.length
        character_position modulo char_range.length
    if character_position < 0 // useful for decoding
        add char_range.length to character_position 
    get new_character at character_position
    append new_character to ciphertext
done

答案 1 :(得分:0)

作为ASCII代码32的空格,您不会过滤掉。你可以尝试:

if (c >= 33 && c <= 127) 
    { 
        // Change base to make life easier, and use an 
        // int explicitly to avoid worrying... cast later 
        int x = c - 32; 
        x = (x + shift) % 96; 
        chars[i] = (char) (x + 32); 
    } 

我刚刚在if-Clause中用33改变了32,这样就可以忽略这些空格。

答案 2 :(得分:0)

你可以用它。它将检查给定的int值是否代表文字。 Character

所以你的功能看起来像这样:

if (Character.isLiteral(c) )
{
     // Change base to make life easier, and use an
     // int explicitly to avoid worrying... cast later
     int x = c - Character.MIN_VALUE;
     x = (x + shift) % Character.MAX_VALUE;
     chars[i] = (char) (x + Character.MIN_VALUE);
}