golang 如何替换掉字符串里面的换行符\n
作者:katy的小乖
这篇文章主要介绍了golang 替换掉字符串里面的换行符\n操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
原始字符串:
-----BEGIN LICENSE KEY-----\nL/+HAwEBB2xpY2Vuc2UB/4gAAQIBB1BheWxvYWQBCgABCVNpZ25hdHVyZQEKAAAA\n/gPo/4gB/gHd/7AQABpsaWNlbnNlLW1nci9jb25maWcuUGF5bG9hZP+BAwEBB1Bh\neWxvYWQB/4IAAQoBBUFwcElkAQwAAQZBcHBLZXkBDAABCVN0YXJ0VGltZQEMAAEE\nRGF5cwEEAAEGQWVzS2V5AQwAAQlIYXNoSWRLZXkBDAABBVRyaWFsAQQAAQVFeHRy\nYQEMAAEKRXhwaXJlVGltZQH/hAABD1Jlc3BvbnNlQ29udHJvbAH/hgAAABD/gwUB\nAQRUaW1lAf+EAAAA/+v/hQMBAQ9SZXNwb25zZUNvbnRyb2wB/4YAAREBBFpvbmUB\nBAABBEFyZWEBBAABCEJ1aWxkaW5nAQQAAQdQb2lOYW1lAQQAAQdBZGRyZXNzAQQA\nAQZTdHJlZXQBBAABCUxvbmdpdHVkZQEEAAEITGF0aXR1ZGUBBAABBUJyYW5kAQQA\nAQlGbG9vck5hbWUBBAABCFByb3ZpbmNlAQQAAQRDaXR5AQQAAQZSZWdpb24BBAAB\nB1BvaUNvZGUBBAABBkNwQ29kZQEEAAELUG9pQ2F0ZWdvcnkBBAABDFBvaUF0dHJp\nYnV0ZQEEAAAALP+CKQEBMQEBMQETMjAxOS0wNS0yOCAyMjowMDowMAECAQExAQEx\nAgExAgAAAf4CAH0RJSpHHmNY/hAQt43pM+qyxZGQ3WzVv1LsaxX55IAqSVHE5w4N\nBmWt3YUt/tG4fy++q1GpWvTsEqAGo1BNTyi/TqK57z5d57GC/gBYlDU8Ke3ZVnyR\n0qWOq5rKdWuMuyNGG9S24U6maaH+sVoumnVSWZohBrOgmjXQ5n2T4c3O+sTjme56\n16UVEXEPR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ZGUBBAABBUJyYW5kAQQA\nAQlGbG9vck5hbWUBBAABCFByb3ZpbmNlAQQAAQRDaXR5AQQAAQZSZWdpb24BBAAB\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
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。