📌  相关文章
📜  如何替换Golang中字节切片中的所有元素?

📅  最后修改于: 2021-10-25 02:52:06             🧑  作者: Mango

在 Go 语言中切片比数组更强大、灵活、方便,是一种轻量级的数据结构。切片是一个可变长度的序列,用于存储相似类型的元素,不允许在同一个切片中存储不同类型的元素。
在 Go 字节切片中,您可以使用ReplaceAll()函数替换给定切片中的所有元素。该函数用于用新切片替换旧切片的所有元素。如果给定的旧切片为空,则它在切片的开头匹配,并且在每个 UTF-8 序列之后,它会为 m-rune 字符串产生最多 m+1 次替换。它是在 bytes 包下定义的,因此您必须在程序中导入 bytes 包才能访问 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