douxie7738 2017-10-26 10:53 采纳率: 0%
浏览 271
已采纳

GoLang在字节片的第N行获取字符串

In a personal project I am implementing a function that returns a random line from a long file. For it to work I have to create a function that returns a string at line N, a second function that creates a random number between 0 and lines in file. While I was implementing those I figured it may be more efficient to store the data in byte slices by default, rather than storing them in separate files, which have to be read at run time.

Question: How would I go about implementing a function that returns a string at a random line of the []byte representation of my file.

My function for getting a string from a file:

func atLine(n int) (s string) {
    f, err := os.Open("./path/to/file")
    if err != nil {
        panic("Could not read file.")
    }
    defer f.Close()
    r := bufio.NewReader(f)
    for i := 1; ; i++ {
        line, _, err := r.ReadLine()
        if err != nil {
            break
        }
        if i == n {
            s = string(line[:])
            break
        }
    }
    return s
}

Additional info:

  • Lines are not longer than 50 characters at most
  • Lines have no special characters (although a solution handling those is welcome)
  • Number of lines in the files is known and so the same can be applied for []byte
  • 写回答

2条回答 默认 最新

  • douzhuo6270 2017-10-26 11:19
    关注

    Dealing with just the question part (and not the sanity of this) - you have a []byte and want to get a specific string line from it - the bytes.Reader has no ReadLine method which you will have already noticed.

    You can pass a bytes reader to bufio.NewReader, and gain the ReadLine functionality you are trying to access.

    bytesReader := bytes.NewReader([]byte("test1
    test2
    test3
    "))
    bufReader := bufio.NewReader(bytesReader)
    value1, _, _ := bufReader.ReadLine()
    value2, _, _ := bufReader.ReadLine()
    value3, _, _ := bufReader.ReadLine()
    fmt.Println(string(value1))
    fmt.Println(string(value2))
    fmt.Println(string(value3))
    

    Obviously it is not sensible to ignore the errors, but for the purpose of brevity I do it here.

    https://play.golang.org/p/fRQUfmZQke

    Results:

    test1
    test2
    test3
    

    From here, it is straight forward to fit back into your existing code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?