Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
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:
- s: This is the reference string.
- old: This is the value in the string we want to change.
- new string: This is the new string value.
- 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.
- 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.
- 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.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.