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
+19.6k Golang : Close channel after ticker stopped example
+6k Golang : Function as an argument type example
+22k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+15.2k Golang : How to check if IP address is in range
+5.7k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+20.7k Golang : Read directory content with os.Open
+14.4k Golang : Find network of an IP address
+41.2k Golang : How to count duplicate items in slice/array?
+6.5k Elasticsearch : Shutdown a local node
+19.2k Golang : Check whether a network interface is up on your machine
+5.4k Golang *File points to a file or directory ?
+15.6k Golang : Validate hostname