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 Golang 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 10, 2022 (edit).