Reputation: 11
I'm creating an app using VB2012 that uses the Atbash Cipher (If ur unfamiliar, it is a cipher where you replace "a" with "z", "b" with "y", etc...) So lets say the code says:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Label1.Text = TextBox1.Text
Label1.Text = Label1.Text.Replace("a", "z")
Label1.Text = Label1.Text.Replace("z", "a")
End Sub
and the textbox read "az". So, by pressing the button, the "a" is replaced by "z", so the message becomes "zz". Then, the second line of code applies, so the "z" is replaced by "a", the message becoming "aa" instead of "za". The question is, how do I run BOTH lines of codes at the same time, so the "a" would become "z" at the same time the "z" becomes an "a". Thank you!
Upvotes: 0
Views: 45
Reputation: 5596
You could use a lookup table and transform the text. When you create a new table object, it will generate the lookup table internally. You can call the instance method Transform on any string argument. This will return the cipher text.
Public Class AtbashTable
''' <summary>
''' Lookup table to shift characters.
''' </summary>
Private _shift As Char() = New Char(Char.MaxValue - 1) {}
''' <summary>
''' Generates the lookup table.
''' </summary>
Public Sub New()
' Set these as the same.
For i As Integer = 0 To Char.MaxValue - 1
_shift(i) = CChar(i)
Next
' Reverse order of capital letters.
For c As Char = "A"C To "Z"C
_shift(CInt(c)) = CChar("Z"C + "A"C - c)
Next
' Reverse order of lowercase letters.
For c As Char = "a"C To "z"C
_shift(CInt(c)) = CChar("z"C + "a"C - c)
Next
End Sub
''' <summary>
''' Apply the Atbash cipher.
''' </summary>
Public Function Transform(value As String) As String
Try
' Convert to char array
Dim a As Char() = value.ToCharArray()
' Shift each letter.
For i As Integer = 0 To a.Length - 1
Dim t As Integer = CInt(a(i))
a(i) = _shift(t)
Next
' Return new string.
Return New String(a)
Catch
' Just return original value on failure.
Return value
End Try
End Function
End Class
Usage in your Button click
event:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AtbashTable x = new AtbashTable();
Label1.Text = x.Transform(TextBox1.Text);
End Sub
Upvotes: 1