replace a substring in a string in go

To replace all occurrences of a substring within a string in Go, you can use the strings.Replace() function. It takes four arguments:

  1. The original string
  2. The substring to be replaced
  3. The replacement string
  4. The number of replacements to make (-1 for all)

Here's an example:

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    original := "the quick brown fox jumps over the lazy dog"
    replaced := strings.Replace(original, "dog", "cat", -1)
    fmt.Println(replaced)
}
214 chars
13 lines

This will output:

main.go
the quick brown fox jumps over the lazy cat
44 chars
2 lines

Note that the Replace() function returns a new string with the replacements made - it does not modify the original string. If you want to modify the original string, you can do something like:

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    original := "the quick brown fox jumps over the lazy dog"
    modified := []rune(original)
    modified = []rune(strings.Replace(string(modified), "dog", "cat", -1))
    fmt.Println(string(modified))
}
270 chars
14 lines

This will output:

main.go
the quick brown fox jumps over the lazy cat
44 chars
2 lines

related categories

gistlibby LogSnag