[英]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.