Go语言学习笔记-A Tour of Go 练习笔记-rot13Reader
创始人
2024-03-08 02:08:05

Exercise: rot13Reader

练习题目:

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 compressed 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 an io.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 mainimport ("io""os""strings"
)type rot13Reader struct {r io.Reader
}func rot13(x byte) byte {switch {case x >= 65 && x <= 77:fallthroughcase x >= 97 && x <= 109:x = x + 13case x >= 78 && x <= 90:fallthroughcase x >= 110 && x <= 122:x = x - 13}return x
}func (rot rot13Reader) Read(a []byte) (int, error) {n, err := rot.r.Read(a)for key, value := range(a) {a[key] = rot13(value)}return n, err
}func main() {s := strings.NewReader("Lbh penpxrq gur pbqr!")r := rot13Reader{s}io.Copy(os.Stdout, &r)
}

运行结果:

You cracked the code!

学习笔记:

该题目是对于GO中Read方法的进阶练习,GO中常用的一种方式是用一个io.Reader去封装另一个io.Reader,这样可以实现很多功能,比如可以先通过里层的io.Reader从加密的文本中先读取加密字符,然后在外层的io.Reader的Read方法中实现解密并输出,这样就完成了一种直接读取解密文本的能力。本题目就是类似的场景,使用的加密算法是比较简单的ROT13字符替换加密法。

相关内容

热门资讯

云南人烤茶,直接用火,就问你野... 原标题:云南人烤茶,直接用火,就问你野不野!——有一种叫云南的生活之365天也许你喝过烤茶但你试过用...
多国代表:祝贺中国! 新华社韩国釜山7月25日电(记者张粲 孙一然)印着“热烈庆祝景德镇申报世界遗产成功”字样的红色横幅,...
网商汇免费发布信息攻略 在网商汇平台,企业可免费发布产品信息,帮助拓展全国市场,触达更广泛客户群体。想知道具体如何操作吗?接...
王嘉尔回应任全球击剑大使 【#王嘉尔回应任全球击剑大使#】#王嘉尔计划2年内开办击剑学校# 7月25日,国际击剑联合会官宣@王...
王毅在马尼拉未与日方会见或交谈 据CGTN最新消息,此次在菲律宾马尼拉期间,王毅外长没有同日方会见的安排,也没有与日方进行交谈。此前...