Replace all spaces in a string with +

29,007

Solution 1

Use strings.ReplaceAll

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)

Solution 2

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)
Share:
29,007
Micheal Perr
Author by

Micheal Perr

Updated on June 11, 2020

Comments

  • Micheal Perr
    Micheal Perr about 4 years

    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