A Tour of Go
Exercise: Rot13 Reader
A common pattern is an io.Reader that wraps another io.Reader, modifying the stream in some way.
For example, the gzip.NewReader function takes an io.Reader (a stream of gzipped data) and returns a *gzip.Reader that also implements io.Reader (a stream of the decompressed data).
Implement a rot13Reader that implements io.Reader and reads from anio.Reader, modifying the stream by applying the ROT13 substitution cipher to all alphabetical characters.
The rot13Reader type is provided for you. Make it an io.Reader by implementing its Read method
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func rot13(p byte) byte {
switch {
case p >= 'A' && p <= 'M': p = p - 'A' + 'N'
case p >= 'N' && p <= 'Z': p = p - 'N' + 'A'
case p >= 'a' && p <= 'm': p = p - 'a' + 'n'
case p >= 'n' && p <= 'z': p = p - 'n' + 'a'
}
return p
}
func (v rot13Reader) Read(p []byte) (n int, err error) {
original := make([]byte, 50)
i, err := v.r.Read(original)
for index, value := range original[:i] {
p[index] = rot13(value)
}
return i, err
}
func main() {
s := strings.NewReader(
"Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}

本文介绍如何使用Go语言实现ROT13替换密码。通过创建一个io.Reader接口的实现,该实现从另一个io.Reader读取数据,并将所有字母字符转换为ROT13密码。文章提供了完整的代码示例,包括如何定义rot13Reader结构体及其Read方法。

2753

被折叠的 条评论
为什么被折叠?



