📌  相关文章
📜  如何在Golang中的字节切片中找到任何元素的最后一个索引值?

📅  最后修改于: 2021-10-24 13:09:30             🧑  作者: Mango

在 Go 语言中切片比数组更强大、灵活、方便,是一种轻量级的数据结构。切片是一个可变长度的序列,用于存储相似类型的元素,不允许在同一个切片中存储不同类型的元素。
在 Go 字节切片中,您可以使用LastIndexAny()函数找到给定切片中任何指定实例的最后一个索引值。此函数返回字符中任何 Unicode 代码点的原始切片中最后一次出现的字节索引。如果来自 chars 的 Unicode 代码点在原始切片中不可用或为空,则此方法将返回-1 。它是在 bytes 包下定义的,因此您必须在程序中导入 bytes 包才能访问 LastIndexAny函数。

句法:

func LastIndexAny(ori_slice []byte, val string) int

这里, ori_slice是原始字符串, val是一个字符串,我们要找到最后一个索引值。让我们在给定示例的帮助下讨论这个概念:

示例 1:

// Go program to illustrate the concept
// of the last index in the slice of bytes
package main
  
import (
    "bytes"
    "fmt"
)
  
func main() {
  
    // Creating and finding the last
    // index of the slice of bytes
    // Using LastIndexAny function
    res1 := bytes.LastIndexAny([]byte("****Welcome to GeeksforGeeks****"),
                                                                 "Gjskf")
      
    res2 := bytes.LastIndexAny([]byte("Learning how to trim a slice of bytes"), 
                                                                       "qoxz")
      
    res3 := bytes.LastIndexAny([]byte("GeeksforGeeks, Geek"), "HELLO")
  
    // Display the results
    fmt.Printf("\nFinal Value:\n")
    fmt.Printf("\nSlice 1: %d", res1)
    fmt.Printf("\nSlice 2: %d", res2)
    fmt.Printf("\nSlice 3: %d", res3)
}

输出:

Final Value:

Slice 1: 27
Slice 2: 29
Slice 3: -1

示例 2:

// Go program to illustrate the concept of
// the last index 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)
  
    // Finding the last index of
    // the slice of bytes
    // Using LastIndexAny function
    res1 := bytes.LastIndexAny(slice_1, "eks")
    res2 := bytes.LastIndexAny(slice_2, "lqzxm")
    res3 := bytes.LastIndexAny(slice_3, "gOlang")
  
    // Display the results
    fmt.Printf("\n\nLast Index:\n")
    fmt.Printf("\nSlice 1: %d", res1)
    fmt.Printf("\nSlice 2: %d", res2)
    fmt.Printf("\nSlice 3: %d", res3)
  
}

输出:

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

Last Index:

Slice 1: 14
Slice 2: 3
Slice 3: 1