Golang 如何替换字节片中的所有元素
在Go语言中slice比数组更强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储相似类型的元素,你不允许在同一个slice中存储不同类型的元素。
在Go的字节片中,你可以使用 ReplaceAll() 函数替换给定slice中的所有元素。这个函数用于用新的片断替换旧片断的所有元素。如果给定的旧片断是空的,那么它在片断的开始处进行匹配,在每个UTF-8序列之后,它最多产生m-rune字符串的m+1替换。它被定义在字节包下,因此,你必须在你的程序中导入字节包以访问RepeatAll函数。
语法
func ReplaceAll(ori_slice, old_slice, new_slice []byte) []byte
这里,ori_slice是原始的字节片,old_slice是你想替换的片,new_slice是替换old_slice的新片。
例1 :
// Go program to illustrate how to replace all
// the specified elements of the slice of bytes
package main
import (
"bytes"
"fmt"
)
// Main function
func main() {
// Creating and initializing
// the slice of bytes
// Using shorthand declaration
slice_1 := []byte{'G', 'G', 'G', 'E',
'E', 'E', 'E', 'K', 'S', 'S', 'S'}
slice_2 := []byte{'A', 'A', 'P',
'P', 'P', 'L', 'E', 'E'}
// Displaying slices
fmt.Println("Original slice:")
fmt.Printf("Slice 1: %s", slice_1)
fmt.Printf("\nSlice 2: %s", slice_2)
// Replacing the element
// of the given slices
// Using ReplaceAll function
res1 := bytes.ReplaceAll(slice_1, []byte("E"), []byte("e"))
res2 := bytes.ReplaceAll(slice_2, []byte("P"), []byte("p"))
// Display the results
fmt.Printf("\n\nNew Slice:")
fmt.Printf("\nSlice 1: %s", res1)
fmt.Printf("\nSlice 2: %s", res2)
}
输出
Original slice:
Slice 1: GGGEEEEKSSS
Slice 2: AAPPPLEE
New Slice:
Slice 1: GGGeeeeKSSS
Slice 2: AApppLEE
例2 :
// Go program to illustrate how to replace all
// the specified elements from the given
// slice of bytes
package main
import (
"bytes"
"fmt"
)
// Main function
func main() {
// Replacing the element
// of the given slices
// Using ReplaceAll function
res1 := bytes.ReplaceAll([]byte("GeeksforGeeks, Geeks, Geeks"), []byte("eks"), []byte("EKS"))
res2 := bytes.ReplaceAll([]byte("Hello! i am Puppy, Puppy, Puppy"), []byte("upp"), []byte("ISL"))
res3 := bytes.ReplaceAll([]byte("GFG, GFG, GFG"), []byte("GFG"), []byte("geeks"))
res4 := bytes.ReplaceAll([]byte("I like like icecream"), []byte("like"), []byte("love"))
// Display the results
fmt.Printf("Result 1: %s", res1)
fmt.Printf("\nResult 2: %s", res2)
fmt.Printf("\nResult 3: %s", res3)
fmt.Printf("\nResult 4: %s", res4)
}
输出
Result 1: GeEKSforGeEKS, GeEKS, GeEKS
Result 2: Hello! i am PISLy, PISLy, PISLy
Result 3: geeks, geeks, geeks
Result 4: I love love icecream
极客教程