Extracting substrings in Go

后端 未结 7 707
甜味超标
甜味超标 2020-12-12 21:12

I\'m trying to read an entire line from the console (including whitespace), then process it. Using bufio.ReadString, the newline character is read together with the input, s

相关标签:
7条回答
  • 2020-12-12 22:17

    8 years later I stumbled upon this gem, and yet I don't believe OP's original question was really answered:

    so I came up with the following code to trim the newline character

    While the bufio.Reader type supports a ReadLine() method which both removes \r\n and \n it is meant as a low-level function which is awkward to use because repeated checks are necessary.

    IMO an idiomatic way to remove whitespace is to use Golang's strings library:

    input, _ = src.ReadString('\n')
    
    // more specific to the problem of trailing newlines
    actual = strings.TrimRight(input, "\r\n")
    
    // or if you don't mind to trim leading and trailing whitespaces 
    actual := strings.TrimSpace(input)
    

    See this example in action in the Golang playground: https://play.golang.org/p/HrOWH0kl3Ww

    0 讨论(0)
提交回复
热议问题