2010-06-14 89 views
1

我讀過this question,我想知道是否有任何方法來考慮整個字符範圍?例如,「á」,「é」,「ö」,「ñ」,而不是「」([Space])? (例如,我的String是「Hello World」,標準結果是「Khoor#Zruog」;我想刪除那個「#」,所以結果將是「KhoorZruog」)Java中的凱撒密碼(西班牙字符)

我確定我的回答是在這段代碼:

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

但我試過一些東西,它沒有奏效。

+0

定義 「全範圍」。我不會考慮「ö」,但會包含「ř」 - 顯然,範圍定義取決於您。 – Piskvor 2010-06-14 12:38:30

+0

此外,「á」,「é」,「ö」或「ñ」在任何地方*關閉*都不是ASCII 32-127;取決於字符集,它們可能在任何地方。只要您離開26個基本拉丁字母,該字符集就不會在所選編碼中形成連續的範圍。 – Piskvor 2010-06-14 13:07:19

回答

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改爲33,以便空格被忽略。

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

當然,雖然這是一個很好的練習,但它不是真正的密碼學 - 即5分鐘內任何人都可以在5分鐘內破解。 – Piskvor 2010-06-14 13:22:54