替换Visual Basic中的每个字符

时间:2016-03-27 15:54:35

标签: vb.net

我想制作一个"加密系统"所以每一个字母都被另一个字母替换。

我们说我们有

Dim encrypt As String = "hi"
encrypt = Replace(encrypt, "h", "i")
encrypt = Replace(encrypt, "i", "j")

而不是成为ij以便将其解密为hi,它变为jj,因为i已加密,但会再次加密。

我该怎么办?

1 个答案:

答案 0 :(得分:2)

实现任务的最简单方法(runnable example):

Imports System.Collections.Generic
Imports System.Linq
Imports System

Public Class Program

    Public Shared Sub Main()
        Dim test As String = "Hi there"
        Dim sb = New System.Text.StringBuilder()
        For Each chr As char In test ' Here you iterate every char in your string
            Select Case chr
                Case "H"
                    sb.Append("i") ' Here you replace your char and append to final result
                    Exit Select
                Case "i"C
                    sb.Append("p")
                    Exit Select
                Case Else
                    sb.Append(chr)
                    Exit Select

            End Select
        Next

        Dim result = sb.ToString()

        Console.WriteLine(result)
    End Sub
End Class

相反,另一个简单的方法是使用字典来映射你的字符,它更好,因为你不必写一个loooong select/case语句(runnable example

Imports System.Collections.Generic
Imports System

Public Class Program

    Public Shared Sub Main()
        ' Here you can declare you char mapping
        Dim mapping As New Dictionary(Of Char, Char)() From { _
            {"H"C, "i"C}, _
            {"i"C, "p"C} _
        }

        ' test input
        Dim test As String = "Hi there"
        Dim sb = New System.Text.StringBuilder()
        ' Here you iterate every char in your string
        For Each chr As Char In test

            ' if a char is mapped
            Dim value As Char
            If mapping.TryGetValue(chr, value) Then
                ' append mapped char to final result
                sb.Append(value)
            Else
                ' otherwise append the original char
                sb.Append(chr)

            End If
        Next

        Dim result As String = sb.ToString()

        Console.WriteLine(result)
    End Sub
End Class