📌  相关文章
📜  如何从 Golang 中的字节切片中修剪前缀?

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

在 Go 语言中切片比数组更强大、灵活、方便,是一种轻量级的数据结构。切片是一个可变长度的序列,用于存储相似类型的元素,不允许在同一个切片中存储不同类型的元素。
在 Go 字节切片中,您可以使用TrimPrefix()函数从给定切片中修剪前缀。此函数通过切掉给定的前导前缀字符串返回原始切片的子切片。如果给定的字节切片不包含指定的前缀字符串,则此函数返回原始切片而不做任何更改。它是在 bytes 包下定义的,因此您必须在程序中导入 bytes 包才能访问 TrimPrefix函数。

句法:

func TrimPrefix(ori_slice, pfx []byte) []byte

这里, ori_slice是原始字节切片,pfx 表示前缀。让我们在给定示例的帮助下讨论这个概念:

示例 1:

// Go program to illustrate the concept of
// trimming prefix in the slice of bytes
package main
  
import (
    "bytes"
    "fmt"
)
  
func main() {
  
    // Creating and trimming the slice of bytes
    // Using TrimPrefix function
    res1 := bytes.TrimPrefix([]byte("****Welcome to GeeksforGeeks****"), 
                                                          []byte("**"))
      
    res2 := bytes.TrimPrefix([]byte("Learning how to trim a slice of bytes"),
                                                            []byte("Learn"))
      
    res3 := bytes.TrimPrefix([]byte("GeeksforGeeks, Geek"), []byte("apple"))
  
    // Display the results
    fmt.Printf("\n\nFinal Slice:\n")
    fmt.Printf("\nSlice 1: %s", res1)
    fmt.Printf("\nSlice 2: %s", res2)
    fmt.Printf("\nSlice 3: %s", res3)
}

输出:

Final Slice:

Slice 1: **Welcome to GeeksforGeeks****
Slice 2: ing how to trim a slice of bytes
Slice 3: GeeksforGeeks, Geek

示例 2:

// Go program to illustrate the concept
// of trimming prefix in the slice of bytes
package main
  
import (
    "bytes"
    "fmt"
)
  
func main() {
  
    // Creating and initializing the slice of bytes
    // Using shorthand declaration
  
    slice_1 := []byte{'!', '!', 'G', 'e', 'e', 'k', 's', 'f', 'o',
                       'r', 'G', 'e', 'e', 'k', 's', '#', '#'}
    slice_2 := []byte{'A', 'p', 'p', 'l', 'e'}
    slice_3 := []byte{'%', 'g', 'e', 'e', 'k', 's', '%'}
  
    // Displaying slices
    fmt.Println("Original Slice:")
    fmt.Printf("Slice 1: %s", slice_1)
    fmt.Printf("\nSlice 2: %s", slice_2)
    fmt.Printf("\nSlice 3: %s", slice_3)
  
    // Trimming specified prefix Unicodes
    // points from the given slice of bytes
    // Using TrimPrefix function
    res1 := bytes.TrimPrefix(slice_1, []byte("!!"))
    res2 := bytes.TrimPrefix(slice_2, []byte("A"))
    res3 := bytes.TrimPrefix(slice_3, []byte("as"))
  
    // Display the results
    fmt.Printf("\n\nNew Slice:\n")
    fmt.Printf("\nSlice 1: %s", res1)
    fmt.Printf("\nSlice 2: %s", res2)
    fmt.Printf("\nSlice 3: %s", res3)
  
}

输出:

Original Slice:
Slice 1: !!GeeksforGeeks##
Slice 2: Apple
Slice 3: %geeks%

New Slice:

Slice 1: GeeksforGeeks##
Slice 2: pple
Slice 3: %geeks%