Golang bytes.Replace() function example
package bytes
Replace returns a copy of the input slice with the first non-overlapping instances of old ( 2nd input parameter) replaced by new (3rd input parameter). The number of replacement (n) is determined by the 4th parameter in the Replace function. If n < 0, there is no limit on the number of replacements.
Golang bytes.Replace() function usage example
package main
import (
"fmt"
"bytes"
)
func main() {
str := []byte("abcdefgh abc abc xyz abc")
replace := bytes.Replace(str, []byte("abc"), []byte("cba"), 2)
fmt.Println(string(replace))
replaceall := bytes.Replace(str, []byte("abc"), []byte("cba"), -1)
fmt.Println(string(replaceall))
}
Output :
cbadefgh cba abc xyz abc
cbadefgh cba cba xyz cba <------ replace all
Reference :
Advertisement
Something interesting
Tutorials
+4.7k Unix/Linux : How to pipe/save output of a command to file?
+40.5k Golang : Convert to io.ReadSeeker type
+12.7k Golang : Sort and reverse sort a slice of bytes
+7.9k Golang : Gomobile init produce "iphoneos" cannot be located error
+24.1k Golang : Upload to S3 with official aws-sdk-go package
+8.6k Golang : Set or add headers for many or different handlers
+30.4k Golang : How to redirect to new page with net/http?
+11.9k Golang : Determine if time variables have same calendar day
+17.9k Golang : Qt image viewer example
+5.6k Golang : Detect words using using consecutive letters in a given string
+6.3k Golang : Test input string for unicode example