String 将字符串中的所有空格替换为+;
我有一个字符串,我想用a+替换该字符串中的每个空格,我通过使用:String 将字符串中的所有空格替换为+;,string,replace,go,String,Replace,Go,我有一个字符串,我想用a+替换该字符串中的每个空格,我通过使用: tw.Text = strings.Replace(tw.Text, " ", "+", 1) 但这对我不起作用…有什么解决办法吗 例如,字符串可能如下所示: The answer of the universe is 42 使用 如果您使用的是较旧版本的go(
tw.Text = strings.Replace(tw.Text, " ", "+", 1)
但这对我不起作用…有什么解决办法吗
例如,字符串可能如下所示:
The answer of the universe is 42
使用
如果您使用的是较旧版本的go(<1.12),请与
-1
一起使用作为限制(无限)
有关
strings.Replace()的文档
:
根据文档,第四个整数参数是替换的数量。您的示例仅将第一个空格替换为“+”。您需要使用小于0的数字,以使其不施加限制:
tw.Text = strings.Replace(tw.Text, " ", "+", -1)
如果在查询中使用此方法,则由
net/url
提供的queryscape
方法是最佳解决方案:
tw.Text = strings.Replace(tw.Text, " ", "+", -1)
tw.Text = strings.Replace(tw.Text, " ", "+", -1)
import "net/url"
tw.Text = url.QueryEscape(tw.Text)