arrays - 如何读取文本文件的每 2 行并保存为字符串数组?
问题描述
我正在尝试将文本文件读入我的程序并将文本文件保存为字符串数组,我已经设法将所有行 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 并将其作为一个保存到数组中。
解决方案
您可以for
通过另一个调用来读取循环中的第二行scanner.Scan
:
var text []string
for scanner.Scan() {
t := scanner.Text()
if scanner.Scan() {
t = t + scanner.Text()
}
text = append(text, t)
}
推荐阅读
- git - VSCode 无法使用 Github
- android - android studio 中的 RemoveBG API
- java - 如何在 Intellij Idea 中更新 PostgreSQL 数据库
- react-native - 我在 React-Native 中遇到了这个意外错误
- amazon-web-services - Elastic Beanstalk 通过 CloudFormation 将标签添加到自动创建的 S3 存储桶
- ios - 正在录制的视频文件上传到服务器
- android - 错误“没有打开应用程序”RobotFramework Mobile 测试脚本在 saucelabs 上执行
- c++ - i+1 之间的差异
我的 C++ 代码
#include <bits/stdc++.h> using namespace std; #define ll long long #define test() ll t; cin>>t; while(t--) int main () { test()
- java - 如何将毫秒转换为模式 mm:ss for kotlin
- python - Python 多处理 Pool.starmap 更改 np.array 列的数据类型