我有一个字符串,想要将其中的每个空格替换为 + ,我试图使用以下代码:
tw.Text = strings.Replace(tw.Text, " ", "+", 1)
但是对我来说那没有起作用...有什么解决方法吗?
例如,字符串可能看起来像:
The answer of the universe is 42
tw.Text = strings.ReplaceAll(tw.Text, " ", "+")
如果您使用的是旧版本的Go语言(< 1.12),请使用 strings.Replace
并将限制(limit)设置为-1
(即无限制)。tw.Text = strings.Replace(tw.Text, " ", "+", -1)
strings.Replace()
的文档: http://golang.org/pkg/strings/#Replace
根据文档,第四个整数参数是替换次数。你的示例只会用“+”替换第一个空格。你需要使用小于0的数字来取消限制。
tw.Text = strings.Replace(tw.Text, " ", "+", -1)
如果您正在查询中使用此功能,则由net/url
提供的QueryEscape
方法是最佳解决方案:https://golang.org/pkg/net/url/#QueryEscape
import "net/url"
tw.Text = url.QueryEscape(tw.Text)