我正在创建一个带加密和解密功能的程序。问题是它应该只对代码上的静态字符串起作用。它应该在输入纯文本是最后一个时循环。例如,字符串是" ABCDE ... Z1234567890"当我输入0并且密钥为2时,密码文本应为B.我有四个文本框用于密钥,输入,明文和密文。这是我的代码。
Public Class Form1
Dim key As Integer
Const Intext As String = "abcdefghijklmnopqrstuvwxyz1234567890"
Private Sub btCipher_Click(sender As Object, e As EventArgs) Handles btCipher.Click
Dim plain, s, r As String
Dim i, j As Long
key = Val(txtKey.Text)
plain = txtInput.Text
For i = 1 To Len(plain)
r = Mid$(plain, i, 1)
j = (InStr(1, Intext, r))
If key > 36 Then
s = s & Mid$(Intext, j + (key - 36), 1)
Else
s = s & Mid$(Intext, j + key, 1)
End If
Next i
txtResult.Text = s
End Sub
Private Sub btDecipher_Click(sender As Object, e As EventArgs) Handles btDecipher.Click
Dim plain, s, r As String
Dim i, j As Long
key = Val(txtKey.Text)
plain = txtResult.Text
For i = 1 To Len(plain)
r = Mid$(plain, i, 1)
j = (InStr(1, Intext, r))
If key > 36 Then
s = s & Mid$(Intext, j + (key - 36), 1)
Else
s = s & Mid$(Intext, j - key, 1)
End If
Next i
txtText.Text = s
End Sub End Class
我的问题是它没有循环。也许有人可以帮忙。谢谢。
答案 0 :(得分:0)
我不确定您的代码无法正常工作,但请尝试使用此代码:
Public Class Form1
Const Intext As String = "abcdefghijklmnopqrstuvwxyz1234567890"
Private Function Transcode(text As String, map As Dictionary(Of Char, Char)) As String
Return New String(text.Select(Function(x) If(map.ContainsKey(x), map(x), x)).ToArray())
End Function
Private Sub btCipher_Click(sender As Object, e As EventArgs) Handles btCipher.Click
Dim key = Val(txtKey.Text)
Dim map = _
Intext _
.Zip(Intext.ToCharArray().Concat(Intext.ToCharArray()).Skip(key), Function(f, t) New With {f, t}) _
.ToDictionary(Function(x) x.f, Function(x) x.t)
txtResult.Text = Transcode(txtInput.Text, map)
End Sub
Private Sub btDecipher_Click(sender As Object, e As EventArgs) Handles btDecipher.Click
Dim key = Val(txtKey.Text)
Dim map = _
Intext _
.Zip(Intext.ToCharArray().Concat(Intext.ToCharArray()).Skip(key), Function(f, t) New With {f, t}) _
.ToDictionary(Function(x) x.t, Function(x) x.f)
txtText.Text = Transcode(txtResult.Text, map)
End Sub
End Class
我测试了算法并且运行正常。