A Tour of Go
Exercise: Rot13 Reader
A common pattern is anio.Readerthat wraps anotherio.Reader, modifying the stream in some way.
For example, thegzip.NewReaderfunction takes anio.Reader(a stream of gzipped data) and returns a*gzip.Readerthat also implementsio.Reader(a stream of the decompressed data).
Implement arot13Readerthat implementsio.Readerand reads from anio.Reader, modifying the stream by applying theROT13substitution cipher to all alphabetical characters.
Therot13Readertype is provided for you. Make it anio.Readerby implementing itsReadmethod
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包装器来读取并转换输入数据。该实现能够将字母表中的每个字母向前移动13个位置。
2753

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



