[英]Java: How do I save seperate lines of text to a string array from a .txt file?
[英]How do I read every 2 lines of a text file and save as a string array?
我正在尝试将文本文件读入我的程序并将文本文件另存为字符串数组,我已经设法将所有行 1 逐 1 读入字符串数组,但我想拥有它,因此它将 2 行读入一个数组。 我的 txt 文件看起来像这样:
line1
line2
line3
line4
fmt.Println(text[0]) 我希望它打印:line1line2
fmt.Println(text[1]) 我希望它打印:line3line4
我目前的代码是:
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var text []string
for scanner.Scan() {
text = append(text, scanner.Text())
}
问题是它正在逐行读取每一行,但我希望它读取 2 并将其作为一个保存到数组中。
您可以通过再次调用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.