OneBite.Dev - Coding blog in a bite size

replace a word in a string in Go

Code snippet on how to replace a word in a string in Go

  package main
  
  import "strings"
  
  func ReplaceWord(s, old, new string) string {
  	return strings.Replace(s, old, new, -1)
  }
  
  func main() {
  	s := "Hello World!"
  	fmt.Println(ReplaceWord(s, "World", "Go")) // Hello Go!
  }

This code will replace the word “World” in the string “Hello World!” with the word “Go”. First, the code imports the strings library so it can use the Replace function. The function ReplaceWord takes a string, an old word to replace, and a new word to replace it with. It then uses the strings library to call the Replace function which is passed the string, the old word, the new word, and -1 which means to replace all occurrences of the old word. The main function creates a string variable s that contains the string “Hello World!“. The main function then calls the ReplaceWord function with the string, “World” to be replaced with “Go”. Finally, the code prints out the result, resulting in “Hello Go!” being printed.

go