Golang 如何替换字节片中的一个指定元素

Golang 如何替换字节片中的一个指定元素

在Go语言中slice比数组更强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储相似类型的元素,你不允许在同一个slice中存储不同类型的元素。

在Go的byte slice中,你可以使用 Replace() 函数替换给定slice中的指定元素。这个函数返回一个包含新片断的副本,新片断是通过替换旧片断中的元素创建的。如果给定的旧片断是空的,那么它在片断的开始处进行匹配,在每个UTF-8序列之后,它最多产生m-rune片断的m+1替换。而如果m的值小于0,那么这个函数可以替换给定片断中的任何数量的元素(没有任何限制)。它被定义在字节包下,因此,你必须在你的程序中导入字节包以访问重复函数。

语法

func Replace(ori_slice, old_slice, new_slice []byte, m int) []byte
Go

这里,ori_slice是原始的字节片,old_slice是你想替换的片,new_slice是替换old_slice的新片,m是替换old_slice的次数。

例1 :

// Go program to illustrate how to replace
// the element 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', 'E', 'E', 'K', 'S'}
    slice_2 := []byte{'A', 'P', 'P', 'L', '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 Replace function
    res1 := bytes.Replace(slice_1, []byte("E"), []byte("e"), 2)
    res2 := bytes.Replace(slice_2, []byte("P"), []byte("p"), 1)
  
    // Display the results
    fmt.Printf("\n\nNew Slice:")
    fmt.Printf("\nSlice 1: %s", res1)
    fmt.Printf("\nSlice 2: %s", res2)
}
Go

输出

Original slice:
Slice 1: GEEKS
Slice 2: APPLE

New Slice:
Slice 1: GeeKS
Slice 2: ApPLE
Go

例2 :

// Go program to illustrate how to replace
// the specified element from the given
// slice of bytes
package main
  
import (
    "bytes"
    "fmt"
)
  
// Main function
func main() {
  
    // Replacing the element
    // of the given slices
    // Using Replace function
    res1 := bytes.Replace([]byte("GeeksforGeeks, Geeks, Geeks"), []byte("eks"), []byte("EKS"), 3)
  
    res2 := bytes.Replace([]byte("Hello! i am Puppy, Puppy, Puppy"), []byte("upp"), []byte("ISL"), 2)
  
    res3 := bytes.Replace([]byte("GFG, GFG, GFG"), []byte("GFG"), []byte("geeks"), -1)
  
    res4 := bytes.Replace([]byte("I like icecream"), []byte("like"), []byte("love"), 0)
  
    // 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)
}
Go

输出

Result 1: GeEKSforGeEKS, GeEKS, Geeks
Result 2:Hello! i am PISLy, PISLy, Puppy
Result 3:geeks, geeks, geeks
Result 4:I like icecream
Go

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册