vb.net中的简单rot13编码器

时间:2012-10-22 17:38:10

标签: vb.net

我正在寻找一种将输入文本编码为Rot13的简单方法。我在能够将单词分成单个字符和整数的阶段撞到砖墙,以便我可以更改每个单词并输出结果。我可以使用单个字母使用下面列出的简单if语句来完成它,但如果有人可以帮助完成整个单词的方式,我会非常感激。

If kInput = "a" then kOutput = "n"

谢谢,凯

3 个答案:

答案 0 :(得分:2)

看起来人们给出了很好的答案,但这是我的尝试。

Dim input As String = "This is a Test!! Guvf vf n Grfg!!"
Dim result As StringBuilder = New StringBuilder()

For Each ch As Char In input

    If (Not Char.IsLetter(ch)) Then
        result.Append(ch)
        Continue For
    End If

    Dim checkIndex As Integer = Asc("a") - (Char.IsUpper(ch) * -32)
    Dim index As Integer = ((Asc(ch) - checkIndex) + 13) Mod 26

    result.Append(Chr(index + checkIndex))

Next

Console.WriteLine(result.ToString())

编辑:改进以消除对大写检查的需要。这将正确处理case和特殊字符,循环内只有1个if语句。

答案 1 :(得分:1)

看起来你正在以这种方式努力。无需分隔单词等,绝对不需要大的If / Else块:

Public Function Rot13(ByVal input As String) As String
    Dim result As Char() = input.ToCharArray()

    For i As Integer = 0 To result.Length - 1
        Dim temp As Integer = Asc(result(i))
        Select Case temp
           Case 65 to 77, 97 To 109 'A - M
               result(i) = Chr(temp + 13)
           Case 78 to 90, 110 To 122 'N - Z
               result(i) = Chr(temp - 13)
        End Select
    Next i

    Return New String(result)
End Function

请注意,这是直接输入浏览器窗口并且未经测试。

答案 2 :(得分:0)

只需调用一次进行编码,再次调用即可解码。

Private Function ROT13_Encode(ByVal Input As String) As String
Dim chrs As Char() = Input.ToCharArray()
Dim ReturnString As String = ""
Dim CharInt As Integer

For Each Chr As Char In chrs
    CharInt = Asc(Chr)
    If CharInt >= 65 And CharInt <= 77 Then 'A-M
        CharInt += 13
    ElseIf CharInt >= 78 And CharInt <= 90 Then 'M-Z
        CharInt -= 13
    ElseIf CharInt >= 97 And CharInt <= 109 Then 'a-m
        CharInt += 13
    ElseIf CharInt >= 110 And CharInt <= 122 Then 'm-z
        CharInt -= 13
    End If
    ReturnString &= ChrW(CharInt)

Next

Return ReturnString
End Function