亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 Go split by newline separator 需要在作為參數接收時進行轉義

為什么 Go split by newline separator 需要在作為參數接收時進行轉義

Go
一只名叫tom的貓 2022-10-10 15:47:21
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


查看完整回答
反對 回復 2022-10-10
?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

您可以嘗試傳遞類似ANSI C 的字符串

go run main.go $'hello\nthere'


查看完整回答
反對 回復 2022-10-10
  • 2 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號