【问题标题】:How do I read every 2 lines of a text file and save as a string array?如何读取文本文件的每 2 行并保存为字符串数组?
【发布时间】:2021-05-16 17:24:35
【问题描述】:

我正在尝试将文本文件读入我的程序并将文本文件保存为字符串数组,我已经设法将所有行 1 逐 1 读取到字符串数组中,但我希望它可以读取2行成一个数组。我的 txt 文件看起来像这样:

line1
line2
line3
line4

fmt.Println(文本[0]) 我希望它打印: line1line2

fmt.Println(文本[1]) 我希望它打印: line3line4

我当前的代码是:

    scanner := bufio.NewScanner(file)
    scanner.Split(bufio.ScanLines)
    var text []string
    for scanner.Scan() {
        text = append(text, scanner.Text())
    }

问题是它会逐行读取每一行,但我希望它读取 2 并将其作为 1 保存到数组中。

【问题讨论】:

    标签: arrays sorting go


    【解决方案1】:

    您可以在for 循环中读取第二行,然后再调用scanner.Scan

    var text []string
    for scanner.Scan() {
        t := scanner.Text()
        if scanner.Scan() {
            t = t + scanner.Text()
        }
        text = append(text, t)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多