How to implement the ROT13 algorithm (replace a letter with the 13th letter after it) in VB.NET

1 Answer

0 votes
Imports System
Imports System.Text

Public Module Rot13Program

    ''' <summary>
    ''' Applies the ROT13 substitution cipher to a string.
    ''' Applying ROT13 twice returns the original text.
    ''' Non-alphabetic characters are left unchanged.
    ''' </summary>
    ''' <param name="input">The text to encode or decode.</param>
    ''' <returns>The ROT13-transformed string.</returns>
    Public Function Rot13(input As String) As String
        If input Is Nothing Then
            Throw New ArgumentNullException(NameOf(input))
        End If

        Dim result As New StringBuilder(input.Length)

        For Each ch As Char In input
            Select Case ch
                Case "A"c To "Z"c
                    result.Append(Convert.ToChar(((Convert.ToInt32(ch) - Convert.ToInt32("A"c) + 13) Mod 26) + Convert.ToInt32("A"c)))

                Case "a"c To "z"c
                    result.Append(Convert.ToChar(((Convert.ToInt32(ch) - Convert.ToInt32("a"c) + 13) Mod 26) + Convert.ToInt32("a"c)))

                Case Else
                    ' Keep numbers, spaces, punctuation, etc. unchanged.
                    result.Append(ch)
            End Select
        Next

        Return result.ToString()
    End Function

	Public Sub Main()
		Dim encoded As String = Rot13Program.Rot13("Hello, World! 123")
		Console.WriteLine(encoded)
		' Uryyb, Jbeyq!

		Dim decoded As String = Rot13Program.Rot13(encoded)
		Console.WriteLine(decoded)
		' Hello, World!
	End Sub

End Module
 
 
' run:
'
' Uryyb, Jbeyq! 123
' Hello, World! 123
'

 



answered 3 days ago by avibootz
edited 1 day ago by avibootz

Related questions

...