Replacing part of the string
Another very common task related to string processing is the replacement of the substring in a string. Go standard library provide the Replace function and Replacer type for the replacement of multiple strings at once.
How to do it...
- Open the console and create the folder
chapter02/recipe06. - Navigate to the directory.
- Create the
replace.gofile with the following content:
package main
import (
"fmt"
"strings"
)
const refString = "Mary had a little lamb"
const refStringTwo = "lamb lamb lamb lamb"
func main() {
out := strings.Replace(refString, "lamb", "wolf", -1)
fmt.Println(out)
out = strings.Replace(refStringTwo, "lamb", "wolf", 2)
fmt.Println(out)
}- Run the code by executing
go run replace.go. - See the output in the Terminal:

- Create the
replacer.gofile with the following content:
package main
import (
"fmt"
"strings...