Simple rot13 encoder in vb.net

前端 未结 3 1692
隐瞒了意图╮
隐瞒了意图╮ 2021-01-29 04:38

I am looking for a simple way to encode an inputted text into Rot13. I am hitting a brick wall at the stage of being able to separate out words into individual characters and in

相关标签:
3条回答
  • 2021-01-29 05:24

    Looks like people are giving good answers to this but here's my try at it.

    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())
    

    EDIT: improved to remove need for uppercase check. This will properly handle case and special characters with only 1 if statement inside the loop.

    0 讨论(0)
  • 2021-01-29 05:27

    It seems like you're making this way harder than it has to be. No need to separate words, etc, and definitely no need for a large If/Else block:

    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
    

    Note that this was entered directly into the browser window and is completely untested.

    0 讨论(0)
  • 2021-01-29 05:32

    Just call it once to encode, call it again to decode.

    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
    
    0 讨论(0)
提交回复
热议问题