string 用 + 替换字符串中的所有空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8689245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:19:29  来源:igfitidea点击:

Replace all spaces in a string with +

stringreplacego

提问by Micheal Perr

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

回答by MikeM

Update:Since go 1.12, please use strings.ReplaceAll(s, old, new string)func ReplaceAll

更新:从 go 1.12 开始,请使用strings.ReplaceAll(s, old, new string)func ReplaceAll

from the Go documentation: func Replace

来自 Go 文档:func Replace

If n < 0, there is no limit on the number of replacements.

如果 n < 0,则替换次数没有限制。

try

尝试

strings.Replace(tw.Text, " ", "+", -1)

回答by C???

Documentation on strings.Replace(): http://golang.org/pkg/strings/#Replace

文档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:

根据文档,第四个整数参数是替换次数。您的示例只会用“+”替换第一个空格。您需要使用小于 0 的数字才能不施加限制:

tw.Text = strings.Replace(tw.Text, " ", "+", -1)

回答by imgrgry

If you are using this in a query, the QueryEscapemethod provided by net/urlis the best solution: https://golang.org/pkg/net/url/#QueryEscape

如果你在查询中使用这个,QueryEscape提供的方法net/url是最好的解决方案:https: //golang.org/pkg/net/url/#QueryEscape

import "net/url"

tw.Text = url.QueryEscape(tw.Text)