package mainimport ( "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,您不需要轉義換行符
2 回答

慕運維8079593
TA貢獻1876條經驗 獲得超5個贊
您假設 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
- 2 回答
- 0 關注
- 141 瀏覽
添加回答
舉報
0/150
提交
取消