Golang 如何找到字节片的第一个索引值

Golang 如何找到字节片的第一个索引值

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

在Go的字节片中,你可以使用 Index() 函数找到给定slice中指定实例的第一个索引值。这个函数返回原始字节片中给定值的第一个实例的索引。如果给定值在原始片断中不可用,则返回-1。它被定义在字节包下,因此,你必须在你的程序中导入字节包以访问Index函数。

语法

func Index(ori_slice, sep_ []byte) int

这里,ori_slice是原始分片,sep_是一个分片,我们想找到其第一个索引值。让我们借助给定的例子来讨论这个概念。

例1 :

// Go program to illustrate the concept
// of the index in the slice of bytes
package main
  
import (
    "bytes"
    "fmt"
)
  
func main() {
  
    // Creating and finding the index 
    // of the slice of bytes
    // Using Index function
    res1 := bytes.Index([]byte("****Welcome to GeeksforGeeks****"), 
                                                    []byte("eek"))
      
    res2 := bytes.Index([]byte("Learning how to trim a slice of bytes"),
                                                          []byte("xzx"))
      
    res3 := bytes.Index([]byte("GeeksforGeeks, Geek"), []byte("eeks"))
  
    // Display the results
    fmt.Printf("\n\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: 16
Slice 2: -1
Slice 3: 1

例2 :

// Go program to illustrate the concept of
// the 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 index of
    // the slice of bytes
    // Using Index function
    res1 := bytes.Index(slice_1, []byte("eek"))
    res2 := bytes.Index(slice_2, []byte("ple"))
    res3 := bytes.Index(slice_3, []byte("xox"))
  
    // Display the results
    fmt.Printf("\n\nFirst 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%

First Index:

Slice 1: 3
Slice 2: 2
Slice 3: -1

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程