3 回答
TA贡献1865条经验 获得超7个赞
我更喜欢在 rot13 函数中直接操作整数
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
const a int = int('a')
const z int = int('z')
const A int = int('A')
const Z int = int('Z')
func rot13(b int) int {
isLower := b >= a && b <= z
isUpper := b >= A && b <= Z
if isLower {
return a + ((b - a + 13) % 26)
}
if isUpper {
return A + ((b - A + 13) % 26)
}
return b
}
func (rot *rot13Reader) Read(b []byte) (int, error) {
n, err := rot.r.Read(b)
if err == io.EOF {
return 0, err
}
for x := range b {
b[x] = byte(rot13(int(b[x])))
}
return n, err
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
- 3 回答
- 0 关注
- 244 浏览
添加回答
举报