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条)

报告相同问题?

悬赏问题

  • ¥15 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!