Home  >  Article  >  Backend Development  >  How to Parse Space-Separated Strings with fmt.Scanln in Go?

How to Parse Space-Separated Strings with fmt.Scanln in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 01:58:01512browse

How to Parse Space-Separated Strings with fmt.Scanln in Go?

How to Parse Space-Separated Strings with fmt.scanln

fmt.scanln is a function used to read input from standard input and scan it into structured variables. However, when reading strings separated by spaces, it may encounter some unexpected behavior.

By default, fmt.scanln stops scanning at the first newline character. This can lead to situations where the user enters a string containing multiple space-separated words, but only the first word is captured.

For example, consider the following code:

<code class="go">package main

import "fmt"

func main() {
    var s string
    fmt.Scanln(&s)
    fmt.Println(s)
    return
}</code>

When the user enters "31 of month", only "31" is captured into the s variable. This occurs because fmt.scanln stops scanning after encountering the space character, which is a whitespace character.

To resolve this issue and capture multiple space-separated words, you can do either of the following:

  1. Use multiple fmt.Scanln statements:

    • This method involves calling fmt.Scanln multiple times to capture each word individually.
    <code class="go">package main
    
    import "fmt"
    
    func main() {
        var s1 string
        var s2 string
        fmt.Scanln(&s1, &s2)
        fmt.Println(s1)
        fmt.Println(s2)
        return
    }</code>
  2. Use a buffered scanner:

    • This alternative uses a buffered scanner to read the entire line of input and then parse the space-separated words.
    <code class="go">package main
    
    import (
        "bufio"
        "fmt"
        "os"
    )
    
    func main() {
        scanner := bufio.NewScanner(os.Stdin)
        for scanner.Scan() {
            s := scanner.Text()
            fmt.Println(s)
        }
        if err := scanner.Err(); err != nil {
            os.Exit(1)
        }
    }</code>

The above is the detailed content of How to Parse Space-Separated Strings with fmt.Scanln in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn