我正在尝试模仿Caesar Cipher加密。问题是每当我输入“wxyz”时
(移位3
)输出为“z {|}”。但预期的输出应该是“zabc”。
任何人都知道要添加什么?
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim plaintext As String = TextBox1.Text
Dim charArray() As Char = plaintext.ToCharArray
Dim shift = TextBox2.Text
Dim character As String
Dim temp As String
TextBox3.Text = ""
If shift <> "" And IsNumeric(shift) Then
If plaintext = "" Then
MsgBox("Please input some plain text")
Exit Sub
End If
If shift > 26 Then
MsgBox("Maximum shifts reached. Limit is 26!!")
Exit Sub
End If
For loope = 0 To charArray.Length - 1 Step +1
temp = charArray(loope)
character = Chr(Asc(temp) + shift)
TextBox3.Text += character
Next
Exit Sub
Else
MsgBox("Input numbers only!!")
End If
End Sub
答案 0 :(得分:0)
当您移动Ascii代码时,您应该验证它不会超过122,这是字符&#34; z&#34;的Ascii代码。如果你超越这一点,你会得到标点符号,符号和那些东西。 Google&#34; ASCII表&#34;你可以自己轻松地看到它。
所以,为了解决你的问题,如果你在转移后获得的Ascii代码大于122,你应该回去再次从97开始,这是&#34; a&#34;的ascii。
所以,而不是:
For loope = 0 To charArray.Length - 1 Step +1
temp = charArray(loope)
character = Chr(Asc(temp) + shift)
TextBox3.Text += character
Next
您应该执行类似
的操作 For loope = 0 To charArray.Length - 1 Step +1
temp = charArray(loope)
character = Chr(Asc(temp) + shift)
' You substract 26, the whole length of the alphabet
If character > 122 Then
character = character - 26
End If
TextBox3.Text += character
Next
如果shift
大于26,则不确定这是否稳定,但无论如何你已经检查了它的值,所以它应该有效。