Go 练习之旅 #23:rot13Reader

我正在尝试解决 Go 练习rot13Reader之旅:


这是我的解决方案:


package main


import (

    "io"

    "os"

    "strings"

)


type rot13Reader struct {

    r io.Reader

}


func rot13(x byte) byte {

    switch {

    case x >= 65 && x <= 77:

        fallthrough

    case x >= 97 && x <= 109:

        x = x + 13

    case x >= 78 && x <= 90:

        fallthrough

    case x >= 110 && x >= 122:

        x = x - 13

    }

    return x

}


func (r13 *rot13Reader) Read(b []byte) (int, error) {

    n, err := r13.r.Read(b)

    for i := 0; i <= n; i++ {

        b[i] = rot13(b[i])

    }

    return n, err

}


func main() {

    s := strings.NewReader("Lbh penpxrq gur pbqr!")

    r := rot13Reader{s}

    io.Copy(os.Stdout, &r)

}

它返回You prnpxrq tur poqr!,这仅表示“Lbh penpxrq gur pbqr!”的第一个单词。裂开了。我怎样才能破解整个句子?


FFIVE
浏览 245回答 3
3回答

莫回无

我更喜欢在 rot13 函数中直接操作整数package mainimport (&nbsp; &nbsp; "io"&nbsp; &nbsp; "os"&nbsp; &nbsp; "strings")type rot13Reader struct {&nbsp; &nbsp; r io.Reader}const a int = int('a')const z int = int('z')const A int = int('A')const Z int = int('Z')func rot13(b int) int {&nbsp; &nbsp; isLower := b >= a && b <= z&nbsp; &nbsp; isUpper := b >= A && b <= Z&nbsp; &nbsp; if isLower {&nbsp; &nbsp; &nbsp; &nbsp; return a + ((b - a + 13) % 26)&nbsp; &nbsp; }&nbsp; &nbsp; if isUpper {&nbsp; &nbsp; &nbsp; &nbsp; return A + ((b - A + 13) % 26)&nbsp; &nbsp; }&nbsp; &nbsp; return b}func (rot *rot13Reader) Read(b []byte) (int, error) {&nbsp; &nbsp; n, err := rot.r.Read(b)&nbsp; &nbsp; if err == io.EOF {&nbsp; &nbsp; &nbsp; &nbsp; return 0, err&nbsp; &nbsp; }&nbsp; &nbsp; for x := range b {&nbsp; &nbsp; &nbsp; &nbsp; b[x] = byte(rot13(int(b[x])))&nbsp; &nbsp; }&nbsp; &nbsp; return n, err}func main() {&nbsp; &nbsp; s := strings.NewReader("Lbh penpxrq gur pbqr!")&nbsp; &nbsp; r := rot13Reader{s}&nbsp; &nbsp; io.Copy(os.Stdout, &r)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go