简体   繁体   中英

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. My txt file would look something like this:

line1
line2
line3
line4

fmt.Println(text[0]) I want it to print: line1line2

fmt.Println(text[1]) I want it to print: 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.

You could just read the second line within your for loop with another call to scanner.Scan :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM