Replacing Parts of a String

28th November 2018 Off By binary
Replacing Parts of a String
trading bonus no deposit

Every developer needs to know how to work with strings in the language they are using. The Go libraries makes replacing parts of strings easy for a developer. I will show three solutions for replacing parts of a string in Go.

Solution 1

The simple way is to use the Replace function from the strings package. This function takes in four values:

  1. s: This is the reference string.
  2. old: This is the value in the string we want to change.
  3. new string: This is the new string value.
  4. n: This is the number of times to do the replacement. If you use -1 it will replace all string values that are equal to the old value

This is the output:

Mary had a little Gopher Gopher duck

If we change line 13 above to:

out := strings.Replace(refString, “duck”, “dog”, -1)

This is the output:

Mary had a little Gopher Gopher Gopher

Solution 2

When you have more than one string value to replace you should use the NewReplacer function from the strings packages. This function returns a new Replacer from a list of old, new string pairs. This method can be use to replace multiple string a once.

This is the output:

John had a little Gopher Gopher

Solution 3

The more sophisticated way of replaces substring is to use regular expression or regex. For this solution, we will use the MustCompile and ReplaceAllString from the regexp package.

  1. MustCompile: Creates our regular expression. In this case, it’s a string that starts with d and is followed by any characters between a and z.
  2. ReplaceAllStrings: This will replace substring that matches the regular expression the string Gopher

This would output:

Mary had a little Gropher Gopher

Originally published at harrisonbrock.com.


Replacing Parts of a String was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.

How to win at binary options?