Golang 教程
Golang 控制语句
Golang 函数 & 方法
Golang 切片 & 数组
Golang 结构体
Golang 字符串
Golang 接口
Golang 指针
Golang 并发
Golang 异常(Error)
Golang 其他杂项

Go 语言切片分割

时间:2023年06月10日 阅读:248
以下内容仅是站长或网友个人学习笔记、总结和研究收藏。不保证正确性,因使用而带来的风险与本站无关!
淘客轩-衣食住行外卖生活好助手

在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() {

    //创建和初始化
    //字节片
    //使用简写声明
    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)

    //分割字节片
    //使用分割函数
    res1 := bytes.Split(slice_1, []byte("eek"))
    res2 := bytes.Split(slice_2, []byte(""))
    res3 := bytes.Split(slice_3, []byte("%"))

    //显示结果
    fmt.Printf("\n\n分割后:")
    fmt.Printf("\nSlice 1: %s", res1)
    fmt.Printf("\nSlice 2: %s", res2)
    fmt.Printf("\nSlice 3: %s", res3)

}

输出:

原始切片:
Slice 1: !!GeeksforGeeks##
Slice 2: Apple
Slice 3: %g%e%e%k%s%

分割后:
Slice 1: [!!G sforG s##]
Slice 2: [A p p l e]
Slice 3: [ g e e k s ]

分割字节切片的方法示例2:

//分割字节切片的方法
package main

import (
    "bytes"
    "fmt"
)

func main() {

    //创建和分割
    //字节片
    //使用分割函数
    res1 := bytes.Split([]byte("****Welcome, to, momojc****"), []byte(","))

    res2 := bytes.Split([]byte("Learning x how x to x trim x a x slice of bytes"), []byte("x"))

    res3 := bytes.Split([]byte("momojc, Geek"), []byte(""))

    res4 := bytes.Split([]byte(""), []byte(","))

    //显示结果
    fmt.Printf("最终结果值:\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)
}

输出:

最终结果值:
Slice 1: [****Welcome  to  momojc****]
Slice 2: [Learning   how   to   trim   a   slice of bytes]
Slice 3: [n h o o o ,   G e e k]
Slice 4: []
打赏

本文地址:https://www.momojc.cn/golang/go-split-a-slice-of-bytes.html

上一篇:Go 语言切片排序

关于本站 | 隐私政策 | 免责声明 | 广告合作 | 我要投稿 | 后台管理

CopyRight © 2023-2024 MOMO教程 WWW.MOMOJC.CN , All Rights Reserved.

站长E-mail:378074730@qq.com 网站已运行:  运行时长:0.044 秒

京ICP备20029690号-1京ICP备20029690号-2 京公网安备11011402013892号京公网安备11011402013892号 中国互联网违法和不良信息举报中心 网络违法犯罪举报网站

本网站托管于 腾讯云 .由网站卫士提供网站加速和攻击防御服务 提供CDN加速/防御服务.由zblogcn强力驱动 又拍云提供CDN加速/云存储服务 51la网站统计