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24BBAAB\nB1BvaUNvZGUBBAABBkNwQ29kZQEEAAELUG9pQ2F0ZWdvcnkBBAABDFBvaUF0dHJp\nYnV0ZQEEAAAALP+CKQEBMQEBMQETMjAxOS0wNS0yOCAyMjowMDowMAECAQExAQEx\nAgExAgAAAf4CAH0RJSpHHmNY/hAQt43pM+qyxZGQ3WzVv1LsaxX55IAqSVHE5w4N\nBmWt3YUt/tG4fy++q1GpWvTsEqAGo1BNTyi/TqK57z5d57GC/gBYlDU8Ke3ZVnyR\n0qWOq5rKdWuMuyNGG9S24U6maaH+sVoumnVSWZohBrOgmjXQ5n2T4c3O+sTjme56\n16UVEXEPRMfAOUaK0Vqte4zpuOuhqQBao0u/nUWBz5zOdlNQYhM5nLWnElmPET8O\namG6FJO16N3UaYaHP+yxlEN4ma1hJUvxm1i5GCEZbOxJY1ke1Dsj3Em3nVg52w4p\ncpAfb5ep9I1xkbavIQ2gxNCjmQG34aDhciVXkEBepVtQZ8ay6b96EiEnhnF72TEy\n/wtxx2p8KoN6wK60PQpW1ZdebROmGOBxQngJkTjjP48gkz+8XaYTpbCMRf4QIbwe\n+QdcnRHm/lgcTY2z98YUaVKmC/TuNzmmaOs/0lPEpq4Z1zgktsCLaMjq6fRjfCOW\n6s4loZhCOh57IlY0AmDuBi2fVwtV7kEyqqxF+2VIOXR/QQakdutfOzimrD3UbZZm\nJOLcbyq1EJjwq+yEs8fXNAhg8lOJMbY8EJ1kNrKjRGUZ82I7WDMYiuZopQNId/HE\nnQDUcLqDQ6x3CCeCVFL+KW5SfVrqwelSaZaeogkHX3RftdIVHhltCwegAA==\n-----END LICENSE KEY-----`
strings.Replace(license, "\n", "", -1)

直接使用\n根本無法替換成功,正確的做法是對\n再進行轉義:\\n

strings.Replace(license, "\\n", "", -1)

補充:golang 字符串去除空格和換行符

字符串去除空格和換行符

package main  
import ( 
  "fmt" 
  "strings" 
) 
 
func main() { 
  str := "這裡是 www\n.jb51\n.net" 
  fmt.Println("-------- 原字符串 ----------") 
  fmt.Println(str) 
  // 去除空格 
  str = strings.Replace(str, " ", "", -1) 
  // 去除換行符 
  str = strings.Replace(str, "\n", "", -1) 
  fmt.Println("-------- 去除空格與換行後 ----------") 
  fmt.Println(str) 
}

輸出結果為:

-------- 原字符串 ----------
這裡是 www
.jb51
.net
-------- 去除空格與換行後 ----------
這裡是www.jb51.net

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: