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

huangapple go评论90阅读模式
英文:

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

使用strings.ReplaceAll

tw.Text = strings.ReplaceAll(tw.Text, " ", "+")

如果你使用的是较旧的 Go 版本(< 1.12),请使用strings.Replace,并将限制参数设置为-1(无限制)

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

Use strings.ReplaceAll

tw.Text = strings.ReplaceAll(tw.Text, &quot; &quot;, &quot;+&quot;)

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, &quot; &quot;, &quot;+&quot;, -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, &quot; &quot;, &quot;+&quot;, -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 &quot;net/url&quot;

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

huangapple
  • 本文由 发表于 2012年1月1日 00:36:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/8689245.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定