Encontrar el valor de índice del byte especificado en una porción de bytes en Golang

El segmento de lenguaje de Go es más poderoso, flexible y conveniente que una array y es una estructura de datos liviana. El segmento es una secuencia de longitud variable que almacena elementos de un tipo similar, no está permitido almacenar diferentes tipos de elementos en el mismo segmento.
En el segmento de bytes Ir, puede encontrar el primer valor de índice del byte especificado en el segmento dado usando la función IndexByte() . Esta función devuelve el índice de la primera instancia del byte especificado en el segmento de bytes dado. Si el byte dado no está disponible en el segmento original, este método devolverá -1 . Se define en el paquete de bytes, por lo que debe importar el paquete de bytes en su programa para acceder a la función IndexByte.

Sintaxis:

func IndexByte(ori_slice []byte, val byte) int

Aquí, ori_slice es el segmento original y val es un byte, cuyo primer valor de índice queremos encontrar. Discutamos este concepto con la ayuda de los ejemplos dados:

Ejemplo 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 IndexByte function
    res1 := bytes.IndexByte([]byte("****Welcome to GeeksforGeeks****"), 
                                                             byte('o'))
      
    res2 := bytes.IndexByte([]byte("Learning how to trim a slice of bytes"),
                                                                 byte('z'))
      
    res3 := bytes.IndexByte([]byte("GeeksforGeeks, Geek"), byte('k'))
  
    // 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)
}

Producción:

Final Value:

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

Ejemplo 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 IndexByte function
    res1 := bytes.IndexByte(slice_1, byte('!'))
    res2 := bytes.IndexByte(slice_2, byte('p'))
    res3 := bytes.IndexByte(slice_3, byte('x'))
  
    // 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)
  
}

Producción:

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

Last Index:

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

Publicación traducida automáticamente

Artículo escrito por ankita_saini y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *