登录
首页 >  Golang >  Go教程

golang 如何替换掉字符串里面的换行符\n

来源:脚本之家

时间:2023-01-07 12:15:09 219浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《golang 如何替换掉字符串里面的换行符\n》,聊聊字符串、换行符、\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++q1GpWvT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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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持golang学习网。如有错误或未考虑完全的地方,望不吝赐教。

终于介绍完啦!小伙伴们,这篇关于《golang 如何替换掉字符串里面的换行符\n》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>