go - 使用换行符解析字符串然后分配给变量
问题描述
我正在尝试将串行输入解析为句子,然后将这些句子分配给一个变量。这是我正在尝试做的一个例子。我的串口当前输出这个:
This is the first sentence.
This is the second sentence.
This is the third sentence.
我阅读并使用以下方法打印它:
scanner := bufio.NewScanner(port)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
我想做的是我想将每个句子分配给一个新变量。我想稍后做这样的事情(示例):
fmt.Printf("First sentence: %q\n", firstSen)
fmt.Printf("Second sentence: %q\n", secondSen)
fmt.Printf("Third sentence: %q\n", thirdSen)
它应该输出:
First sentence: This is the first sentence.
Second sentence: This is the second sentence.
Third sentence: This is the third sentence.
我该怎么做呢?谢谢你。
解决方案
从输入中收集行:
var lines []string
scanner := bufio.NewScanner(port)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
// handle error
}
循环遍历变量,为变量分配一行:
var firstSen, secondSen, thirdSen string
for i, s := range []*string{&firstSen, &secondSen, &thirdSen} {
if i >= len(lines) {
break
}
*s = lines[i]
}
如问题所示打印:
fmt.Printf("First sentence: %q\n", firstSen)
fmt.Printf("Second sentence: %q\n", secondSen)
fmt.Printf("Third sentence: %q\n", thirdSen)
根据您的要求,您可以删除变量并直接使用行切片:
fmt.Printf("First sentence: %q\n", line[0])
fmt.Printf("Second sentence: %q\n", line[1])
fmt.Printf("Third sentence: %q\n", line[2])
推荐阅读
- c - C:如何在 gtk 中制作上下文菜单
- php - 我的 laravel 查询生成器有问题
- rxjs - 如何在nestjs拦截器中的takeUntil之后返回其他内容
- clojure - 如何在 Clojure 中遍历多个分支树并收集数据?
- visual-studio-code - babel-loader@8.2.2 需要 webpack@>=2 的 peer 但没有安装
- mysql - 如何设置一个从 MySQL 数据库自动更新自身的新 MySQL 数据库?
- java - runOnUiThread - 不会运行
- cordova - 为什么创建科尔多瓦应用程序不起作用?
- asp.net - 在 TypeScript 中使用 Sys.WebForms.PageRequestManager
- visual-c++ - 安装程序无法安装以下组件:Microsoft 应用程序错误报告