Golang
Replace substring in Golang
Replace substring with other substring.Replace method included in strings package returns 1st argument whose substring specified as 2nd argument is replaced with substring specified as 3rd argument.
Replacing is performed times specified as 4th argument.
If 4th argument is smaller than 0, replacing with no limit.
replace_string.go
package main import ( "fmt" "strings" ) func main() { // Target string str := "dog cat dog" // Show original string fmt.Println(str) // Replace one dog to panda fmt.Println(strings.Replace(str, "dog", "panda", 1)) // Replace two dogs to panda fmt.Println(strings.Replace(str, "dog", "panda", 2)) // Replace no dog fmt.Println(strings.Replace(str, "dog", "panda", 0)) // Replace dog to panda infinitely fmt.Println(strings.Replace(str, "dog", "panda", -1)) }
Result
$ go run replace_string.go dog cat dog panda cat dog panda cat panda dog cat dog panda cat panda