C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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?
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.
Instead: Methods like strings.Map are ideal for transforming strings based on characters.