OneBite.Dev - Coding blog in a bite size

replace a substring within a string in Go

Code snippet on how to replace a substring within a string in Go

  s := "This is a string"
  newS := strings.Replace(s, "string", "sentence", 1)
  fmt.Println(newS)

This code sample replaces a substring within a string using the Go programming language. First, we declare a new string, s, and assign it a value of “This is a string”. Then, we use the strings.Replace function from the strings package to replace the substring “string” with “sentence” once in s, and assign the replaced string to newS. Finally, we use the fmt.Println function to print out the new string newS, which will have the value of “This is a sentence”.

go