如何将字符串转换为不同的字符?

时间:2015-01-20 11:25:31

标签: vb.net

我在网上看过,找不到任何可以帮助我的东西,我能找到的就是将字符改成ASCII或十六进制。但是我想以不同的方式做到这一点。例如,假设传入的字符串是abcdef,我希望有一个键将这些字符更改为另一个字符串,例如qwpolz。是否有一种比将字母表中的每个字符声明为另一个字符更简单的方法,如:

Dim sText As String = "Hello"
Dim sEncode As String = ""
Dim iLength As Integer
Dim i As Integer
iLength = Len(sText)

For i = 1 To iLength
    sEncode = sEncode ????
Next
    Return sEncode

然后有一个非常冗长的循环来检查这些循环?必须有一个更简单的方法。任何人都能指点我正确的方向吗?

编辑:为什么要downvote?说真的,这是一个合理的问题。而不是无缘无故地贬低,只是转向另一个问题。

2 个答案:

答案 0 :(得分:1)

听起来好像要根据映射表将每个字符替换为不同的字符来修改字符串。一种有效的方法是使用Dictionary(Of Char, Char)。但更容易编写和维护是这样的:

Shared ReadOnly replaceChars As String = "abcdef"
Shared ReadOnly withChars As String = "qwpolz"

Public Shared Function ReplaceAll(input As String) As String
    Dim newChars = From c In input
                   Let index = replaceChars.IndexOf(c)
                   Select If(index >= 0, withChars(index), c)
    Return String.Concat(newChars)
End Function

因此第一个字符串包含要替换的字符,第二个字符串包含替换字符。两个字符串必须具有相同的长度。

如果您想支持不区分大小写:

Public Shared Function ReplaceAll(input As String, comparison As StringComparison) As String
    Dim newChars = From c In input
                   Let index = replaceChars.IndexOf(c.ToString(), comparison)
                   Select If(index >= 0, withChars(index), c)
    Return String.Concat(newChars)
End Function

请注意,这也是一个循环。如果要替换多个字符或字符串,则无法避免某种循环。

答案 1 :(得分:1)

实际上,这听起来像Caesar sipher

enter image description here

Private Overloads Shared Function Encrypt(ByVal ch As Char, ByVal code As Integer) As Char
    If Not Char.IsLetter(ch) Then
        Return ch
    End If
    Dim offset As Char = IIf(Char.IsUpper(ch), "A", "a")
    Return CType((((ch + (code - offset)) Mod 26) + offset),Char)
End Function

Private Overloads Shared Function Encrypt(ByVal input As String, ByVal code As Integer) As String
    Return New String(input.ToCharArray.Select(() => {  }, Encrypt(ch, code)).ToArray)
End Function

Private Shared Function Decrypt(ByVal input As String, ByVal code As Integer) As String
    Return Encrypt(input, (26 - code))
End Function

请注意,这假定您使用英文字母。在一般情况下,例如你有'ä','ö','š','ž','ß','õ','ü'等,这是行不通的。在这种情况下,只需创建有序字母表的列表/字典并使用它就更简单。

使用示例:

encrypted = Encrypt(sText, 5)
decypted = Decrypt(encrypted, 5)
相关问题