1

アルファベットを一定量シフトするこのコードがあります。アルファベットのサイズは26です。より大きなサイズシフト(たとえば22)を入力すると、奇妙な文字が表示されます。ASCIIアルファベットを26に変更する必要があると思いますが、どのビットを変更するかはよくわかりません。

基本的に、アルファベットを折り返す必要があります(Zに達すると、文字Aに戻ります)modが機能するための辞書を作成する必要がありますか(A = 0 ... Z = 26など)、または使用を続けることができますか?通常のASCIIテーブル?以下のコードは次のとおりです。

Public Function encrypt(ByVal input As String) 'input is a variable within the funcion
    Dim n as Integer
    Dim i As Integer
    n = key.Text Mod 26 'gets what is in the text box of 'key' and sets it as n
    ' the key is a multiple of 26 so 26 will  = 0

    'need to remove white spaces
    While input.Contains(" ")           'when the input text contains a space
        input = input.Replace(" ", "")  'replaces it with no space.
    End While


    For i = 1 To Len(input)                                     'find the length of the input
        Mid(input, i, 1) = Chr(Asc(Mid(input, i, 1)) + n)       'chr returns the character associated with the specified character code
        '
    Next
    encrypt = input
End Function
4

1 に答える 1

3

このコードを見てください:

For i = 1 To Len(input)                                     'find the length of the input
    Mid(input, i, 1) = Chr(Asc(Mid(input, i, 1)) + n)       'chr returns the character associated with the specified character code
    '
Next

文字列インデックスは0 ベースです。最初のインデックスは 1 ではなく 0 です! また、関数呼び出しの結果に割り当てています。代わりに、新しい文字列を作成する必要があります。

あなたは言いませんでしたが、Replace メソッドと Contains メソッドを使用した方法は .Net を示しています。その場合は、次のようにします。

Public Function encrypt(ByVal key As Integer, ByVal input As String) As String 'Don't forget the return type on the function
    key = key Mod 26
    Return New String(input.Replace(" ", "").ToUpper().Select(Function(c) Chr(((Asc(c) + key - Asc("A"c)) Mod 26) + Asc("A"c))).ToArray())
End Function

そのように、それはほとんどワンライナーです。次のように呼び出すと、これが機能することがわかります。

Encrypt("C"c, "the quick brown fox jumps over the lazy dog")
Encrypt("D"c, "the quick brown fox jumps over the lazy dog")

結果:

BPMYCQKSJZWEVNWFRCUXMLWDMZBPMTIHGLWOA
CQNZDRLTKAXFWOXGSDVYNMXENACQNUJIHMXPB

「lazy」という単語にマップされた結果を探します。「a」が「z」と「y」に正しくラップされ、「D」キーの結果が「C」の結果から 1 文字ずれていることがわかります。 .

于 2012-04-10T15:58:24.117 に答える