paint-brush
Replacing Parts of a Stringby@harrison_brock
850 reads
850 reads

Replacing Parts of a String

by Harrison BrockNovember 28th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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.
featured image - Replacing Parts of a String
Harrison Brock HackerNoon profile picture

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

<a href="https://medium.com/media/43d9351ad089b4470f014a0ae8bd5466/href">https://medium.com/media/43d9351ad089b4470f014a0ae8bd5466/href</a>

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.

<a href="https://medium.com/media/d6abfd854b89c827ad40411162c62836/href">https://medium.com/media/d6abfd854b89c827ad40411162c62836/href</a>

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

<a href="https://medium.com/media/e44a348cecd264aeebdd47a502bdb947/href">https://medium.com/media/e44a348cecd264aeebdd47a502bdb947/href</a>

This would output:

Mary had a little Gropher Gopher

Originally published at harrisonbrock.com.