英文:
Replace all spaces in a string with +
问题
我有一个字符串,我想用+替换这个字符串中的每个空格。我尝试使用以下代码:
tw.Text = strings.Replace(tw.Text, " ", "+", 1)
但是这对我没有起作用...有什么解决办法吗?
例如,字符串可能是这样的:
宇宙的答案是42
英文:
I have a string and I want to replace every space in this string with a + I tired this by using:
tw.Text = strings.Replace(tw.Text, " ", "+", 1)
But that didn't worked for me...any solutions?
For example the string could look like:
The answer of the universe is 42
答案1
得分: 55
tw.Text = strings.ReplaceAll(tw.Text, " ", "+")
如果你使用的是较旧的 Go 版本(< 1.12),请使用strings.Replace
,并将限制参数设置为-1
(无限制)
tw.Text = strings.Replace(tw.Text, " ", "+", -1)
英文:
tw.Text = strings.ReplaceAll(tw.Text, " ", "+")
If you're using an older version of go (< 1.12), use strings.Replace
with -1
as limit (infinite)
tw.Text = strings.Replace(tw.Text, " ", "+", -1)
答案2
得分: 6
根据文档,第四个整数参数是替换的次数。你的示例只会将第一个空格替换为“+”。你需要使用一个小于0的数字来取消限制:
tw.Text = strings.Replace(tw.Text, " ", "+", -1)
英文:
Documentation on strings.Replace()
: http://golang.org/pkg/strings/#Replace
According to the documentation, the fourth integer parameter is the number of replacements. Your example would only replace the first space with a "+". You need to use a number less than 0 for it to not impose a limit:
tw.Text = strings.Replace(tw.Text, " ", "+", -1)
答案3
得分: 1
如果您在查询中使用此代码,net/url
提供的 QueryEscape
方法是最佳解决方案:https://golang.org/pkg/net/url/#QueryEscape
import "net/url"
tw.Text = url.QueryEscape(tw.Text)
英文:
If you are using this in a query, the QueryEscape
method provided by net/url
is the best solution: https://golang.org/pkg/net/url/#QueryEscape
import "net/url"
tw.Text = url.QueryEscape(tw.Text)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论