简体   繁体   English

如何读取文本文件的每 2 行并保存为字符串数组?

[英]How do I read every 2 lines of a text file and save as a string array?

I'm trying to read a text file into my program and save the text file as a string array, I have managed to achieve reading all lines into a string array 1 by 1 but I would like to have it so it reads 2 lines into one array.我正在尝试将文本文件读入我的程序并将文本文件另存为字符串数组,我已经设法将所有行 1 逐 1 读入字符串数组,但我想拥有它,因此它将 2 行读入一个数组。 My txt file would look something like this:我的 txt 文件看起来像这样:

line1
line2
line3
line4

fmt.Println(text[0]) I want it to print: line1line2 fmt.Println(text[0]) 我希望它打印:line1line2

fmt.Println(text[1]) I want it to print: line3line4 fmt.Println(text[1]) 我希望它打印:line3line4

My current code is:我目前的代码是:

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

The issue is it's reading each line one by one but I'd want it to read 2 and save it into the array as one.问题是它正在逐行读取每一行,但我希望它读取 2 并将其作为一个保存到数组中。

You could just read the second line within your for loop with another call to scanner.Scan :您可以通过再次调用scanner.Scan来读取for循环中的第二行:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java:如何将单独的文本行从.txt文件保存到字符串数组? - Java: How do I save seperate lines of text to a string array from a .txt file? 如何将文本文件中的单个行保存在数组中? - How do i save individual lines from a text file in an array? 如何读取文本文件图像并将其保存到数组? - How do I read a text file image and save it to an array? 如何在文本文件中读取行列表的位置 - How do I read a position of a list of lines in text file 如何从文件中读取行并将其存储到数组中 - How do I read lines from a file and store them into an array 如何用空行将文本文件拆分为数组? - How do I split a text file into an array by blank lines? 如何从file.csv读取并将每个值保存在数组C的字符串中 - How to read from a file.csv and save every value in a string of array C 在Java中,我需要读取一个文本文件并将每一行放在单独的数组中。 但是每次阅读文本文件时,我都无法分开 - In Java I need to read a text file and put each line in a separate array. But every time I read the text file I cannot split the lines 读取文本文件,然后每7行创建一个“页面” - Read a text file and create a 'Page' every 7 lines 如何将字符串数组(从文本文件中读取)更改为 Int 数组? 这样我就可以搜索和排序数据 - How do I change a String Array (being read from a text file) to a Int Array? So that I can search and sort the data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM