In this section, we're going to see how we can quickly replace a part of a string with another value. When it comes to string manipulation in Go language, you will find a lot of utility methods under the strings package. Herein, we are going to use the same package for replacing a part of the string with another value. Let's go back to our editor and see how we can commence this process.
So, I'm going to have a helloWorld
variable and we're going to replace World with Mars. Check the following code:
package main import ( "strings" "fmt" ) func main(){ helloWorld := "Hello, World" helloMars := strings.Replace(helloWorld, "World", "Mars", 1) fmt.Println(helloMars) }
The following screenshot will explain the code that we just looked at:
As shown in the screenshot, we're going to use strings
package and it has a replace
function and it accepts the variable that we're going to search as the first parameter, which is Hello, World. The old string would be the things...