如何循环特定的字符串凯撒密码 vb10



>我正在创建一个带有加密和解密功能的程序。问题是它应该只对代码上的静态字符串起作用。当输入纯文本是最后一个时,它应该循环。例如,字符串是"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

我的问题是它没有循环。也许有人可以帮忙。谢谢。

我不确定为什么你的代码不起作用,但请尝试以下代码:

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

我已经测试了算法,它工作正常。

最新更新