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.
Note The Map 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.
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)
}Do you have any cat pictures?
Qb lbh unir nal png cvpgherf?
Some details. In the Go strings package documentation, a ROT13 example is presented for the Map method. This uses more complex logic, with modulo division.
Tip I prefer simpler if-else statements when possible—these are easier to reason about for new developers.
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.
Detail 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 10, 2022 (edit).