HomeSearch

Golang ROT13 Method

This Go example uses the strings.Map method to apply the rot13 cipher.
ROT13. This cipher obscures the characters in a string. With ROT13, characters are rotated 13 places in the alphabet. Other characters are not changed.
In Go, a method in the strings package can be used to translate strings. This is the Map method. It receives a func that receives a rune, and returns a translated one.
Example method. First we define the rot13 method. This receives a rune and returns a rune. It contains the translation logic for the rotation of characters.

Strings.Map: This method is part of the "strings" package. The first argument is a func that translates a rune.

Result: The program correctly applies the rot13 transformation. The input string is obscured.

Golang program that translates strings with ROT13 package main import ( "fmt" "strings" ) func rot13(r rune) rune { if r >= 'a' && r <= 'z' { // Rotate lowercase letters 13 places. if r >= 'm' { return r - 13 } else { return r + 13 } } else if r >= 'A' && r <= 'Z' { // Rotate uppercase letters 13 places. if r >= 'M' { return r - 13 } else { return r + 13 } } // Do nothing. return r } func main() { input := "Do you have any cat pictures?" mapped := strings.Map(rot13, input) fmt.Println(input) fmt.Println(mapped) } Output Do you have any cat pictures? Qb lbh unir nal png cvpgherf?
Some details. In the Golang strings package documentation, a ROT13 example is presented for the Map method. This uses more complex logic, with modulo division.Strings: golang.org

Tip: I prefer simpler if-else statements when possible. You don't need to be a genius to figure these out.

And: Simplicity, I think, is more important than having fewer lines of code in a method.

For ROT13 methods, a translation method is usually the clearest approach. A new string could be built up, in a loop over the characters, but this is less clear.

Instead: Methods like strings.Map are ideal for transforming strings based on characters.

Summary. ROT13 is not a secure cipher. It can easily be reversed. But it might help reduce casual snooping on a piece of text. And it helps us learn about string transformation methods.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls