package main
import (
"fmt"
"os"
"strings"
)
func main() {
arguments := os.Args
words := strings.Split(arguments[1], "\n")
fmt.Println(words)
fmt.Println(words[0])
}
例子:
go run main.go "hello\nthere"
輸出:
[hello\nthere]
hello\nthere
預期的:
[hello there]
hello
為什么"\n"需要轉義換行符的分隔符"\\n"才能獲得預期結果?
因為如果像這樣使用,您不需要轉義換行符https://play.golang.org/p/UlRISkVa8_t
uj5u.com熱心網友回復:
您可以嘗試傳遞ANSI C 之類的字串
go run main.go $'hello\nthere'
uj5u.com熱心網友回復:
您假設 Go 將您的輸入視為:
"hello\nthere"
但它確實將您的輸入視為:
`hello\nthere`
因此,如果您希望將該輸入識別為換行符,則需要取消參考它。但那是一個問題,因為它也沒有引號。因此,您需要添加引號,然后將其洗掉,然后才能繼續您的程式:
package main
import (
"fmt"
"strconv"
)
func unquote(s string) (string, error) {
return strconv.Unquote(`"` s `"`)
}
func main() {
s, err := unquote(`hello\nthere`)
if err != nil {
panic(err)
}
fmt.Println(s)
}
結果:
hello
there
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/334887.html
標籤:走
