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 :

http://golang.org/pkg/bytes/#Replace

Advertisement