English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在Go字节片段中,允许您使用Split()函数分割给定的切片。此函数将字节的切片拆分为由给定分隔符分隔的所有子切片,并返回包含所有这些子切片的切片。它在bytes包下定义,因此,您必须在程序中导入bytes包才能访问Split函数。
语法:
func Split(o_slice, sep []byte) [][]byte
在这里,o_slice是字节片,sep是分隔符。如果sep为空,则它将在每个UTF-8序列之后拆分。让我们借助给出的示例来讨论这个概念:
字节切片分割示例:
//分割字节片的方法 package main import ( "bytes" "fmt" ) func main() { //创建和初始化 //Segmento di byte //使用简写声明 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', '%'} //显示切片 fmt.Println("原始切片:") fmt.Printf("Slice 1: %s", slice_1) fmt.Printf("\nSlice 2: %s", slice_2) fmt.Printf("\nSlice 3: %s", slice_3) //分割字节片 //Usa la funzione di divisione res1 := bytes.Split(slice_1, []byte("eek")) res2 := bytes.Split(slice_2, []byte("")) res3 := bytes.Split(slice_3, []byte("%")) //Mostra il risultato fmt.Printf("\n\nDopo la divisione:") fmt.Printf("\nSlice 1: %s", res1) fmt.Printf("\nSlice 2: %s", res2) fmt.Printf("\nSlice 3: %s", res3) }
Output:
Segmento originale: Slice 1: !!GeeksforGeeks## Slice 2: Apple Slice 3: %g%e%e%k%s% Dopo la divisione: Slice 1: [!!G sforG s##] Slice 2: [A p p l e] Slice 3: [g e e k s]
Metodo di divisione dei segmenti di byte esempio 2:
//Metodo di divisione dei segmenti di byte package main import ( "bytes" "fmt" ) func main() { //Creazione e divisione //Segmento di byte //Usa la funzione di divisione res1 := bytes.Split([]byte("****Welcome, to, w3codebox****"), []byte(",")) res2 := bytes.Split([]byte("Learning x how x to x trim x a x slice x of x bytes"), []byte("x")) res3 := bytes.Split([]byte("w3codebox, Geek"), []byte("")) res4 := bytes.Split([]byte(""), []byte(",")) //Mostra il risultato fmt.Printf("Valore finale:\n") fmt.Printf("\nSlice 1: %s", res1) fmt.Printf("\nSlice 2: %s", res2) fmt.Printf("\nSlice 3: %s", res3) fmt.Printf("\nSlice 4: %s", res4) }
Output:
Valore finale: Slice 1: [****Benvenuti a w3codebox****] Slice 2: [Imparare come tagliare un pezzo di byte] Slice 3: [n h o o o, G e e k] Slice 4: []