您的位置:首页 > 编程语言 > Go语言

go语言Exercise: Rot13 Reader

2012-05-09 16:24 387 查看
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 an
io.Reader
, modifying the stream by applying the ROT13substitution cipher to all alphabetical characters.
The
rot13Reader
type is provided for you. Make it an
io.Reader
by
implementing its
Read
method.
加密方法:凯撒加密,key为13

package main

import (

"io"

"os"

"strings"

)

type rot13Reader struct {

r io.Reader

}

func Rot13(b byte) byte {

switch {

case 'A' <= b && b <= 'M':

b = b + 13

case 'M' < b && b <= 'Z':

b = b - 13

case 'a' <= b && b <= 'm':

b = b + 13

case 'm' < b && b <= 'z':

b = b - 13

}

return b

}

func (read *rot13Reader) Read(p []byte) (n int, err error){

n, err = read.r.Read(p)

for i, value := range p {

p[i] = Rot13(value)

}

return

}

func main() {

s := strings.NewReader(

"Lbh penpxrq gur pbqr!")

r := rot13Reader{s}

io.Copy(os.Stdout, &r)

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: