【问题标题】:Parse string using newline delimiter then assign to variables使用换行符解析字符串然后分配给变量
【发布时间】:2018-05-31 21:41:26
【问题描述】:

我正在尝试将串行输入解析为句子,然后将这些句子分配给一个变量。这是我正在尝试做的一个例子。我的串口目前输出这个:

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.

我该怎么做呢?谢谢。

【问题讨论】:

    标签: go string-parsing


    【解决方案1】:

    从输入中收集行:

    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])
    

    【讨论】:

    • 谢谢!虽然我现在面临一个问题。如果我使用这两种方法中的任何一种,似乎什么都没有打印出来。也许这与通过串口获取输入有关?
    • 使用iotest.NewReadLogger 记录从端口读取的数据。 scanner := bufio.NewScanner(iotest.NewReadLogger("port", port))。如果不符合您的预期,请从那里进行调试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2017-07-02
    • 2013-02-25
    • 2013-02-23
    • 1970-01-01
    • 2011-01-20
    相关资源
    最近更新 更多