Нахождение значения индекса указанного байта в срезе байтов в Golang

Опубликовано: 20 Февраля, 2022

В языке Go фрагмент более мощный, гибкий, удобный, чем массив, и представляет собой легкую структуру данных. Срез представляет собой последовательность переменной длины, в которой хранятся элементы аналогичного типа, вам не разрешается хранить элементы разных типов в одном срезе.
В срезе байтов Go вы можете найти первое значение индекса указанного байта в данном срезе с помощью функции IndexByte () . Эта функция возвращает индекс первого экземпляра указанного байта в заданном срезе байтов. Если данный байт недоступен в исходном срезе, этот метод вернет -1 . Он определен в пакете байтов, поэтому вам необходимо импортировать пакет байтов в свою программу для доступа к функции IndexByte.

Синтаксис:

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

Здесь ori_slice - это исходный срез, а val - байт, для которого мы хотим найти первое значение индекса. Обсудим эту концепцию с помощью приведенных примеров:

Example 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(" Final Value: ")
    fmt.Printf(" Slice 1: %d", res1)
    fmt.Printf(" Slice 2: %d", res2)
    fmt.Printf(" Slice 3: %d", res3)
}

Выход:

Конечное значение:

Срез 1: 8
Срез 2: -1
Срез 3: 3

Example 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(" Slice 2: %s", slice_2)
    fmt.Printf(" Slice 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(" Last Index: ")
    fmt.Printf(" Slice 1: %d", res1)
    fmt.Printf(" Slice 2: %d", res2)
    fmt.Printf(" Slice 3: %d", res3)
  
}

Выход:

Исходный фрагмент:
Часть 1: !! GeeksforGeeks ##
Ломтик 2: яблоко
Срез 3:% компьютерщиков%

Последний индекс:

Срез 1: 0
Срез 2: 1
Срез 3: -1