go语言Exercise: Rot13 Reader
2012-05-09 16:24
387 查看
A common pattern is an io.Reader that wraps another
modifying the stream in some way.
For example, the gzip.NewReader function takes an
stream of gzipped data) and returns a
the decompressed data).
Implement a
reads from an
The
implementing its
加密方法:凯撒加密,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)
}
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.Readerthat also implements
io.Reader(a stream of
the decompressed data).
Implement a
rot13Readerthat implements
io.Readerand
reads from an
io.Reader, modifying the stream by applying the ROT13substitution cipher to all alphabetical characters.
The
rot13Readertype is provided for you. Make it an
io.Readerby
implementing its
Readmethod.
加密方法:凯撒加密,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)
}
相关文章推荐
- A Tour of Go: Exercise: Rot13 Reader
- A Tour of Go: Exercise: Rot13 Reader
- go语言Advanced Exercise: Complex cube roots
- go语言Exercise: Errors
- go语言Exercise: Images
- Go语言之Writer 和 Reader
- Go语言中io.Reader和io.Writer的详解与实现
- Go 语言实现exercise--Loops and Functions
- go语言Exercise: Equivalent Binary Trees
- Exercise: Rot13 Reader
- go语言Reader包封
- Go语言中异步拆分io.Reader
- go语言Exercise: Maps
- go语言Exercise: Slices
- go语言Exercise: Fibonacci closure
- Go语言学习
- Go语言反射规则 - The Laws of Reflection
- go语言学习道路1-学习前
- 在 go/golang语言中使用 google Protocol Buffer
- Go 语言开发环境设置(Fedora x64)