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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵