¿Cómo recortar los espacios en blanco de la 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 la porción de bytes Go, se le permite recortar todos los espacios en blanco iniciales y finales de la porción dada usando la función TrimSpace() . Esta función devuelve un subsector del segmento original eliminando todos los espacios en blanco iniciales y finales. 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 TrimSpace.

Sintaxis:

func TrimSpace(ori_slice []byte) []byte

Aquí, ori_slice es el segmento de bytes original. Discutamos este concepto con la ayuda de los ejemplos dados:

Ejemplo 1:

// Go program to illustrate the concept of
// trimming white space 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 whitespace from
    // the given slice of bytes
    // Using TrimSpace function
    res1 := bytes.TrimSpace(slice_1)
    res2 := bytes.TrimSpace(slice_2)
    res3 := bytes.TrimSpace(slice_3)
  
    // 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)
  
}

Producción:

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

New Slice:

Slice 1: !!GeeksforGeeks##
Slice 2: **Apple^^
Slice 3: %geeks%

Ejemplo 2:

// Go program to illustrate the concept of
// trimming white space in the slice of bytes
package main
  
import (
    "bytes"
    "fmt"
)
  
func main() {
  
    // Creating and trimming whitespace
    // from the given slice of bytes
    // Using TrimSpace function
    res1 := bytes.TrimSpace([]byte(" ****Welcome to GeeksforGeeks**** "))
    res2 := bytes.TrimSpace([]byte(" !!!!Learning how to trim a slice of bytes@@@@ "))
    res3 := bytes.TrimSpace([]byte(" Geek, GeeksforGeeks "))
  
    // 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)
}

Producción:

Final Slice:

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

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 *