繁体   English   中英

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

[英]Caesar Cipher in Java (Spanish Characters)

我已经阅读了这个问题 ,我想知道是否有任何方法可以考虑整个字符范围? 例如,“á”,“é”,“ö”,“ñ”,而不考虑“”([空格])? (例如,我的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);
        }

但是我已经尝试了一些方法,但是没有用。

参见以下伪代码-应该可以轻松实现:

// 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

不过滤的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中用32更改了32,以便简单地忽略空格。

您可以使用它。 它将检查您是否给定的int值表示文字。 字符

因此您的函数可能如下所示:

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM